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). You should note that this behavior results from the operators and not the kind of string used.
The following program repeats the simple program used to demonstrate the failure of the extractor when used with C-strings but with a string object as the target:
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) |