14: cout << “Enter string two: “;
15: cin >> stringTwo;
16: cout << “StringTwo: “ << stringTwo << endl;
17: return 0;
18: }
Enter string one: Now is the time
stringOne: Now is the time
Enter string two: For all good
StringTwo: For
On lines 7 and 8, two character arrays are created. On line 10, the user is
prompted to enter a string, and cin.get()is called on line 11. The first parame-
ter is the buffer to fill, and the second is one more than the maximum number for get()
to accept (the extra position being given to the null character, [‘\0’]). There is not a third
parameter shown; however, this is defaulted. The defaulted third parameter is a newline.
The user enters “Now is the time.” Because the user ends the phrase with a newline,
that phrase is put into stringOne, followed by a terminating null.
The user is prompted for another string on line 14, and this time the extraction operator
is used. Because the extraction operator takes everything up to the first whitespace, only
the string For, with a terminating null character, is stored in the second string, which, of
course, is not what was intended.
Using get()with the three parameters is perfectly valid for obtaining strings; however, it
is not the only solution. Another way to solve this problem is to use getline(), as illus-
trated in Listing 17.7.
LISTING17.7 Using getline()
0: // Listing 17.7 - Using getline()
1:
2: #include <iostream>
3: using namespace std;
4:
5: int main()
6: {
7: char stringOne[256];
8: char stringTwo[256];
9: char stringThree[256];
10:
11: cout << “Enter string one: “;
12: cin.getline(stringOne,256);
OUTPUT
608 Day 17
LISTING17.6 continued
ANALYSIS