简体   繁体   中英

Why can't use std::cin by setting std::cin.clear() after a wrong input?

I read the example code from https://en.cppreference.com/w/cpp/io/basic_ios/clear and tried this:

command line input is: w

#include <iostream>
#include <string>

int main()
{
    double n = 5.0;
    std::cin >> n;
    std::cout << std::cin.bad() << "|" << std::cin.fail() << "\n";
    std::cout << "hello" << "\n";
    std::cin.clear();
    std::cout << std::cin.bad() << "|" << std::cin.fail() << "\n";
    std::cin >> n;   //Why can't I input again here?
    std::cout << "world" << "\n";
    std::cout << n << "\n";
}

I don't understand why the program finishes without allowing me to input again, I think I've use std::cin.clear() to reset all the "fail" states.

clear just resets the error-flags, but it leaves the previous input, which had led to the failure, in the buffer. Hence, the second cin >> n will again read the same input and will again fail. So you will not get the chance to enter new input.

You need to take errorneous characters from the buffer (in addition to calling cin.clear() ); Use, for example, cin.ignore(std::numeric_limits<std::streamsize>::max(), '\\n') , which ignores every character until the first occurence of a \\n . You could also use fgets , but - in contrast to ignore - fgets requires a buffer to store characters in which you are actually not interested.

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