std::cin doesn't throw an exception on bad input

前端 未结 2 581
天命终不由人
天命终不由人 2020-12-20 00:34

I am just trying to write a simple program that reads from cin, then validates that the input is an integer. If it does, I will break out of my while loop. If not, I will as

2条回答
  •  误落风尘
    2020-12-20 01:03

    C++ iostreams don't use exceptions unless you tell them to, with cin.exceptions( /* conditions for exception */ ).

    But your code flow is more natural without the exception. Just do if (!(cin >> input)), etc.

    Also remember to clear the failure bit before trying again.

    The whole thing can be:

    int main()
    {
        int input;
        do {
           cout << "Please enter an integral value \n";
           cin.clear();
           cin.ignore(std::numeric_limits::max(), '\n');
        } while(!(cin >> input));
        cout << input;
        return 0;
    }
    

提交回复
热议问题