Cin overflowing into following cin

user12322544

I have a simple program that works nominally when the input is precisely as expected.

#include <iostream>
using namespace std;

int main ()
{
    int a, b;
    char ab;

    cin >> a;
    cin >> ab;
    cin >> b;

    cout << a;
    cout << ab;
    cout << b;
}

This works perfectly when the inputs are normal; however, when the second cin runs, it will input the remainder into the next cin call.

So output of this case would look like:

4
454

4
4
54

How do I deal with the extra in the cin buffer to keep it from going into the next one?

Mert Köklü

Instead of cin you can use getline:

string input;
getline(cin, input);

In this way, you will take input as line so you won't bother with buffer or anythink else. After that, you can parse it.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related