Rick
Rick

Reputation: 7506

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.

Upvotes: 1

Views: 158

Answers (1)

Stephan Lechner
Stephan Lechner

Reputation: 35154

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.

Upvotes: 4

Related Questions