2

Please read the following code:

#include <iostream>
#include <cstdlib>
int main() {
    std::cout << "Please input one integer." << std::endl;
    int i;
    while (true) {
        std::cin >> i;
        if (std::cin) {
            std::cout << "i = " << i << std::endl;
            break;
        } else {
            std::cout << "Error. Please try again."<< std::endl;
            std::cin.ignore();
            std::cin.clear();
        }
    }
    std::cout << "Thank you very much." << std::endl;
    std::system("pause");
    return 0;
}

When I give std::cin an invalid input, such as w, then Error. Please try again. is outputed infinitely. I thought std::cin.ignore would blank the input stream, and std::cin.clear would resume it to normal state. So why does the infinite loop happen?

Dannyu NDos
  • 2,458
  • 13
  • 32

1 Answers1

4

By default, std::basic_istream::ignore() ignores only 1 character:

basic_istream& ignore( std::streamsize count = 1, int_type delim = Traits::eof() );

(From http://en.cppreference.com/w/cpp/io/basic_istream/ignore)

More idiomatic use for your case seems to be the one from the example there:

cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

Also, note that you want to call clear() before the ignore() call, so the input extraction of ignore() will succeed instead of returning immediately.

Yehezkel B.
  • 1,140
  • 6
  • 10