Working with Streams 611
17
17: cout << “\n\nNow try again...\n”;
18:
19: cout << “Enter string one: “;
20: cin.get(stringOne,255);
21: cout << “String one: “ << stringOne<< endl;
22:
23: cin.ignore(255,’\n’);
24:
25: cout << “Enter string two: “;
26: cin.getline(stringTwo,255);
27: cout << “String Two: “ << stringTwo<< endl;
28: return 0;
29: }
Enter string one:once upon a time
String one: once upon a time
Enter string two: String two:
Now try again...
Enter string one: once upon a time
String one: once upon a time
Enter string two: there was a
String Two: there was a
On lines 6 and 7, two character arrays are created. On line 9, the user is
prompted for input and types once upon a time, followed by pressing the Enter
key. On line 10,get()is used to read this string. get()fills stringOneand terminates
on the newline, but leaves the newline character in the input buffer.
On line 13, the user is prompted again, but the getline()on line 14 reads the input
buffer up to the newline. Because a newline was left in the buffer by the call to get(),
line 14 terminates immediately, before the user can enter any new input.
On line 19, the user is prompted again and puts in the same first line of input. This time,
however, on line 23,ignore()is used to empty the input stream by “eating” the newline
character. Thus, when the getline()call on line 26 is reached, the input buffer is empty,
and the user can input the next line of the story.
Peeking at and Returning Characters:peek()and putback()......................
The input object cinhas two additional methods that can come in rather handy:peek(),
which looks at but does not extract the next character, and putback(), which inserts a
character into the input stream. Listing 17.9 illustrates how these might be used.
OUTPUT
LISTING17.8 continued
ANALYSIS