Search code examples
c++

Entering an Integer then a string with spaces in C++


How can I input an integer, then a string "with spaces"?

Here is what I've tried:

    int x;
    string s;
    cout << "Enter Integer" << endl;
    cin >> x;
    cout << "Enter the string with spaces" << endl;
    // "cin >> s;" doesn't read the text after the first space
    // "getline(cin,s);" doesn't seem to read anything

Solution

  • The problem you are likely having is that the cin >> x reads only the digits of the number you type, and not the following newline. Then, when you do a cin >> s to read a string, the input processor sees the newline and returns only an empty string.

    The solution is to use a function that is designed to read whole lines of input, such as std::getline. Do not use the extraction operator >> for interactive input.