Previously, we explored the behavior of C-string console I/O. We discovered that the inserter operator, <<, worked well for C-string output. However, the extractor operator, >>, didn't work reliably for C-string input. Specifically, the extractor fails to read white space (spaces and tabs). This behavior is due to the operators, not the type of string used.
The following example repeats the simple program used to demonstrate the failure of the extractor used in conjunction with C-strings, but with a string object as the target:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string input;
//cin >> input; // stops reading at space
//cout << input << endl;
getline(cin, input); // discards \n
cout << input << endl;
return 0;
}
>>, again fails to read spaces into a string object just as it failed to read spaces into a C-string. In the earlier C-string example, we solved the problem with a function named getline, and we'll take the same approach here. But notice that we're using a different getline function here despite having the same name.
The following figure compares the two getline functions side by side to highlight their differences.
| C-String | string Class |
|---|---|
char input[100]; cin.getline(input, 100); |
string input; getline(cin, input); |
|
|
![]() | ||
#include <iostream>
#include <string>
using namespace std;
int main()
{
int i1;
cout << "Enter the first number: ";
cin >> i1;
string s1;
cout << "Enter the first string: ";
getline(cin, s1);
cout << s1 << endl;
return 0;
}
|
#include <iostream>
#include <string>
using namespace std;
int main()
{
int i1;
cout << "Enter a number: ";
cin >> i1;
cin.ignore();
string s1;
cout << "Enter the first string: ";
getline(cin, s1);
cout << s1 << endl;
return 0;
} |
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1;
cout << "Enter the first string: ";
cin.ignore();
getline(cin, s1);
cout << s1 << endl;
return 0;
}
|
| (a) | (b) | (c) |