Declaring, Initializing, Printing, and Reading Strings
Now we’ll learn to store string values. C++ has a string class. Think of it as a type like int or double. This class allows one to declare objects (which we will treat like variables of data type string) and provides methods (or member functions) for manipulating strings. To use strings, you must #include<string>. The string header file includes the prototypes for the string functions, just as cmath contains the prototypes for mathematical functions, and iostream contains the prototypes for I/O functions.
Declaring, Initializing, Printing, and Reading Strings:
#include <iostream>
#include <string>
int main()
{
string str1, str2;
str1 = "Hello";
str2 = "Harry";
cout << str1 << ", " < < str2 << endl;
return 0;
}
This will print "Hello, Harry" and go to a new line.
You can
• Initialize a string in the declaration
• Assign the value of one string to another,
• Send a string to cout
• Read in a string from cin – don’t need to type the quotes
But cin stops reading as soon as a whitespace (space, tab, or newline) character is encountered. This is quite limiting if you want to read in someone's full name or a sentence.
getline(input_stream, string_variable, delimiting_character);
getline() reads characters (including whitespace characters) from the input_stream into the specified string_variable until the delimiting_character is encountered. The third parameter is optional. If it is omitted, the default is the newline character.
string name;
getline(cin,name);
cout << name << endl;
reads until it encounters the newline (i.e. the user hits "Enter"). The ‘\n’ is read but not stored in name.
The optional third parameter can be any character used as a delimiter. getline() reads until it encounters the delimiter, which is not stored in the string.
string first, second;
getline(cin, first,',');
getline(cin, second,'D');
Thus, if the line typed in was "Hello, John Doe" followed by a newline character, first would get the value "Hello" and second would get " John ", including space before 'J' and the space after 'n'. Neither string would include the comma because that was the delimiter.
ignore() Warning, warning, warning:
Not in the book, but necessary: if you try to use getline after >>, it will read whatever is left on the line, even if it is just a newline character. You have to use the function ignore() (in <iostring>) to ignore the rest of the line and go to the beginning of the next line.
cin.ignore(numchars,char);
ignore() skips the number of characters specified or all of the characters up to and including the character specified by the second parameter, whichever comes first.
For example,
cin.gnore(80,’\n’);
skips 80 characters or goes to the beginning of the next line.
Use infile.ignore(100,’\n’); if you are reading from infile rather than the keyboard.