Working with Streams 601
17
must have enough room in the buffer to allow for the entire string plus the null. The null
signals the “end of string” to the cinobject.
String Problems ..............................................................................................
After all this success with cin, you might be surprised when you try to enter a full name
into a string. cinhas trouble getting the full name because it believes that any white-
space is a separator. When it sees a space or a new line, it assumes the input for the para-
meter is complete, and in the case of strings, it adds a null character right then and there.
Listing 17.2 illustrates this problem.
LISTING17.2 Trying to Write More Than One Word to cin
0: //Listing 17.2 - character strings and cin
1:
2: #include <iostream>
3:
4: int main()
5: {
6: char YourName[50];
7: std::cout << “Your first name: “;
8: std::cin >> YourName;
9: std::cout << “Here it is: “ << YourName << std::endl;
10: std::cout << “Your entire name: “;
11: std::cin >> YourName;
12: std::cout << “Here it is: “ << YourName << std::endl;
13: return 0;
14: }
Your first name: Jesse
Here it is: Jesse
Your entire name: Jesse Liberty
Here it is: Jesse
On line 6, a character array called YourNameis created to hold the user’s input.
On line 7, the user is prompted to enter one name, and that name is stored prop-
erly, as shown in the output.
On line 10, the user is again prompted, this time for a full name. cinreads the input, and
when it sees the space between the names, it puts a null character after the first word and
terminates input. This is not exactly what was intended.
To understand why this works this way, examine Listing 17.3, which shows input for
several fields.
OUTPUT
ANALYSIS