user12322544
user12322544

Reputation:

Cin overflowing into following cin

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?

Upvotes: 0

Views: 96

Answers (1)

Mert K&#246;kl&#252;
Mert K&#246;kl&#252;

Reputation: 2231

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.

Upvotes: 1

Related Questions