Sams Teach Yourself C++ in 21 Days

(singke) #1
Working with Streams 609

17


13: cout << “stringOne: “ << stringOne << endl;
14:
15: cout << “Enter string two: “;
16: cin >> stringTwo;
17: cout << “stringTwo: “ << stringTwo << endl;
18:
19: cout << “Enter string three: “;
20: cin.getline(stringThree,256);
21: cout << “stringThree: “ << stringThree << endl;
22: return 0;
23: }

Enter string one: one two three
stringOne: one two three
Enter string two: four five six
stringTwo: four
Enter string three: stringThree: five six
This example warrants careful examination; some potential surprises exist. On
lines 7–9, three character arrays are declared this time.
On line 11, the user is prompted to enter a string, and that string is read by using get-
line(). Like get(),getline()takes a buffer and a maximum number of characters.
Unlike get(), however, the terminating newline is read and thrown away. With get(),
the terminating newline is not thrown away. It is left in the input buffer.
On line 15, the user is prompted for the second time, and this time the extraction opera-
tor is used. In the sample output, you can see that the user enters four five six; how-
ever, only the first word,four, is put in stringTwo. The string for the third prompt,
Enter string three, is then displayed, and getline()is called again. Because five
sixis still in the input buffer, it is immediately read up to the newline; getline()termi-
nates and the string in stringThreeis printed on line 21.
The user has no chance to enter the third string because the input buffer contained data
that fulfilled the request this prompt was making.
The call to cinon line 16 did not use everything that was in the input buffer. The extrac-
tion operator (>>) on line 16 reads up to the first whitespace and puts the word into the
character array.

OUTPUT


LISTING17.7 continued


ANALYSIS
Free download pdf