c++user-inputcin

When I enter 2 integer inputs with a space it jumps to the second cin function


So when I try to input the required inputs for program I want user to enter them one by one. And when I enter the both of them at once with a space between them like:

5 10

It directly goes to the second cin's end.

#include <iostream>

using namespace std;

int main() {
    int asd1, asd2;

    cout << "Enter the first one: ";
    cin >> asd1;
    cout << endl;
    if (asd1 == 5) {
        cout << "First one is 5" << endl;
    }

    cout << "Enter the second one: ";
    cin >> asd2;
    cout << endl;
    if (asd2 == 10) {
        cout << "Second one is 10" << endl;
    }
}

And when I enter two inputs together it outputs with a ugly way which is why I'm asking this.

Output:

Enter the first one: 5 10

First one is 5
Enter the second one:         <<<< Here it doesn't cin.
Second one is 10

I tried using cin.get() but didn't really work.


Solution

  • The first read statement: cin >> asd1 reads 5 from the buffer, but leaves 10 in that buffer. The second read statement: cin >> asd2 is able to immediately read 10 from the buffer without any further action being necessary.

    If you wish to ignore the rest of that 5 10 input, you need to read the entire line into a string using std::get line, then parse the first int out and assign that to asd1 and asd2.

    For instance, you might write a function to do this. Bear in mind this has zero error checking.

    #include <iostream>
    #include <sstream>
    #include <string>
    
    int get_int_line(std::istream &in) {
        std::string line;
        std::getline(in, line);
        std::istringstream sin(line);
        int i;
        sin >> i;
        
        return i;
    } 
    

    At which point you could just write:

    int asd1 = get_int_line(std::cin);