How to reset std::cin when using it?

2019-01-12 07:45发布

问题:

I have some problem with following code. I use it in Xcode (OS X).

[removed my first try of that code]

How to input reset std::cin? I try to input another values but I can't because std::cin seems to not work anymore after my wrong value.

UPD2 In my second try I use this code:

for ( unsigned char i = 0; i < 5; i++ ) {

    int value = 0;

    std::cout << "\n>> Enter \"value\": ";
    std::cin >> value;

    if ( std::cin.fail() ) {
        std::cin.clear();
        std::cin.ignore();
        std::cout << "Error: It's not integer value!\n";
    } else {
        std::cout << "The value format is ok!\n";
    }

    std::cout << "value = " << value << std::endl;

}

Here I just input 5 values in a loop. Everytime I check it on error. When I set the wrong value ("asdf") std::cin goes crazy and doesn't work anymore. I get this output:

>> Enter "value": 4
The value format is ok!
value = 4

>> Enter "value": 234
The value format is ok!
value = 234

>> Enter "value": asdfghjkl
Error: It's not integer value!
value = 0

>> Enter "value": Error: It's not integer value!
value = 0

>> Enter "value": Error: It's not integer value!
value = 0
234
234
78
345
657
345
dsf
f

回答1:

You could use, when the condition, std::cin.fail() happens:

std::cin.clear();
std::cin.ignore();

And then continue with the loop, with a continue; statement. std::cin.clear() clears the error flags, and sets new ones, and std::cin.ignore() effectively ignores them (by extracting and discarding them).

Sources:

  1. cin.ignore()
  2. cin.clear()


标签: c++ std cin