Download presentation
Presentation is loading. Please wait.
1
Using string type variables
Section day 1 Using string type variables
2
The ASCII Character Set
41 = ')'
3
Using string: Input and Output
#include <iostream> #include <string> using namespace std; int main() { string name; cout << "Enter your name: "; cin >> name; cout << "Your name is " << name << endl; return 0; } >> reads a word up to a space or newline character Type the above code into a new project. The next slide will tell us what else we need to do before compilation.
4
Using string: getline #include <iostream> #include <string> int main() { string name; cout << "Enter your full name: "; getline(cin, name); cout << "Your full name is " << name << endl; return 0; } getline reads an entire line, including blanks, up to a newline character
5
Using >> Before getline
#include<iostream> #include<string> // program segment below string name; int age; cout << "Enter your age: "; cin >> age; cout << "Enter your full name: "; getline(cin, name); cout << "Your age is " << age << endl; cout << "Your full name is " << name << endl; Do you see any problems with this segment of code? Type and run a program that includes this segment. getline encounters the trailing newline after the age, stores an empty string in name, and does not wait for user input
6
Reverse the order of the inputs, with getline being called before >>.
apstring name; int age; cout<<"Enter your full name:"; getline(cin,name); cout<<"Enter your age:"; cin>>age; cout << name << “,you are ”<<age<<endl;
7
Or use cin.ignore(); before getline
#include <iostream> #include <string> string name; int age; cout << "Enter your age: "; cin >> age; cin.ignore(); // consume \n cout << "Enter your full name: "; getline(cin, name); cout << "Your age is " << age << endl; cout << "Your full name is " << name << endl;
8
Memory for String Variables
When a string variable is declared, no memory is initially provided. When a value is assigned to a string variable, the computer automatically adjusts the memory to accommodate the number of characters to be stored.
9
apstring Member Functions
10
Group Activity Write a program that will prompt the user for the name of the school and save it into a single variable of the string data type. Your program will output the users school name and the string length as you see below: Your school name is NA Intermediate High School. There are 27 characters in this name. (including space characters) Raise your hand when your program functions properly.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.