Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset std::cin when using it?

Tags:

c++

std

cin

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

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

    std::cout << ">> Enter \"value\": ";
    std::cin >> value;
    
    if ( std::cin.fail() ) { 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. See this:

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

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

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

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

>> Enter "value": Error: It's not integer value!
value = 0
80
32423
adf
3843
asdf
asdf
23423

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.

like image 988
JavaRunner Avatar asked Sep 16 '25 14:09

JavaRunner


1 Answers

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()
like image 181
Arnav Borborah Avatar answered Sep 19 '25 04:09

Arnav Borborah