How to reset std :: cin when using?

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

[deleted my first attempt at this code]

How to enter reset std :: cin? I am trying to enter other values, but I cannot, because std :: cin does not seem to work anymore after my incorrect value.

UPD2 In the second attempt, 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 not integer value!\n";
    } else {
        std::cout << "The value format is ok!\n";
    }

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

}

Here I just enter 5 values ​​in a loop. Every time I check it for an error. When I set the wrong value ("asdf"), std :: cin goes crazy and no longer works. 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 not integer value!
value = 0

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

>> Enter "value": Error: It not integer value!
value = 0
234
234
78
345
657
345
dsf
f
+1
source share
1 answer

You can use when a condition std::cin.fail()occurs:

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

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

:

+4

Source: https://habr.com/ru/post/1694890/


All Articles