简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM