Mixing String and Numeric Input

Mixing numeric input with line-oriented string input can cause problems. Consider the simple program in Listing 4.6.

Listing 4.6. numstr.cpp

// numstr.cpp -- following number input with line input#include <iostream>int main(){    using namespace std;    cout << "What year was your house built?\n";    int year;    cin >> year;    cout << "What is its street address?\n";    char address[80];    cin.getline(address, 80);    cout << "Year built: " << year << endl;    cout << "Address: " << address << endl;    cout << "Done!\n";    return 0;}

Running the program in Listing 4.6 would look something like this:

What year was your house built?1966What is its street address?Year built: 1966AddressDone!

You never get the ...

Get C++ Primer Plus now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.