Adventures in String Input

The strings.cpp program has a blemish that is concealed through the often useful technique of carefully selected sample input. Listing 4.3 removes the veils and shows that string input can be tricky.

Listing 4.3. instr1.cpp


// 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: ";
    cin >> name;
    cout << "Enter your favorite dessert: ";
    cin >> dessert;
    cout << "I have some delicious " << dessert;
    cout << " for you, " << name << ". ";
    return 0;
}


The intent of the program in Listing 4.3 is simple: Read a user’s name and favorite dessert from the keyboard and then display the information. Here is a sample run:

Enter your name:
Alistair Dreeb
Enter your favorite dessert:
I have some delicious Dreeb for you, Alistair.

We didn’t even get a chance to respond to the dessert prompt! The program showed it and then immediately moved on to display the final line.

The problem lies with how cin determines when you’ve finished entering a string. You can’t enter the null character from the keyboard, so cin needs some other means for locating the end of a string. The cin technique is to use whitespace—spaces, tabs, and newlines—to delineate a string. This means cin reads just one word when it gets input for a character array. After it reads this word, cin automatically adds the terminating null character when it places the string into the array.

The practical result in this example is that cin reads Alistair as the entire first string and puts it into the name array. This leaves poor Dreeb still sitting in the input queue. When cin searches the input queue for the response to the favorite dessert question, it finds Dreeb still there. Then cin gobbles up Dreeb and puts it into the dessert array (see Figure 4.4).

Figure 4.4. The cin view of string input.

Image

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 offers no protection against placing a 30-character string in a 20-character array.

Many programs depend on string input, so it’s worthwhile to explore this topic further. We’ll have to draw on some of the more advanced features of cin, which are described in Chapter 17, “Input, Output, and Files.”

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.168.214