How to reset std::cin when using it?

10,586

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()
Share:
10,586
JavaRunner
Author by

JavaRunner

Updated on June 04, 2022

Comments

  • JavaRunner
    JavaRunner almost 2 years

    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.