(A-1) shows that string input
- Can be tricky
Example of (A-1)
// instr1.cpp -- reading more than one string #include <iostream> int main() { using namespace std; const int ArSize = 20; char name[ArSize]; char dessert[ArSize]; cout << "Enter your name:\n"; cin >> name; cout << "Enter your favorite dessert:\n"; cin >> dessert; cout << "I have some delicious " << dessert; cout << " for you, " << name << ".\n"; return 0; }
The intent of the program in (A-1) is simple:
- Read a user’s name and favorite dessert from the keyboard and then display the information (B-1)
Here is a sample run (A-1):

Program Notes (A-1)
- (B-1) We didn’t even get a chance to respond to the dessert prompt (B-2)
- (B-2) The program showed it and then immediately moved on to display the final line (B-3)
- (B-3) The problem lies with how cin determines when you’ve finished entering a string (B-4)
- (B-4) You can’t enter the null character from the keyboard (B-5)
- (B-5) cin needs some other means for locating the end of a string (B-6)
- (B-6) The cin technique (B-7)
- (B-7) Is to use whitespace—spaces, tabs, and newlines—to delineate a string (B-8)
- (B-8) This means cin reads just one word when it gets input for a character array (B-9)
- (B-9) After it reads this word, cin automatically adds the terminating null character when it places the string into the array (B-10)
- (B-10) The practical result in this example (B-11)
- (B-11) Is that cin reads Bjarne as the entire first string and puts it into the name array (B-12)
- (B-12) This leaves poor Stroustrup still sitting in the input queue (B-13)
- (B-13) When cin searches the input queue for the response to the favorite dessert question, it finds Stroustrup still there (B-14)
- (B-14) Then cin gobbles up Stroustrup and puts it into the dessert array (Image-1)
- (B-11) Is that cin reads Bjarne as the entire first string and puts it into the name array (B-12)
(Image-1) The cin view of string input

Another problem, which didn’t surface in the sample run
- Is that the input string might turn out to be longer than the destination array
- Using cin as this example did offer no protection against placing a 30-character string in a 20-character array

Discussion
No comments for “Adventures in String Input”