How to use cin.fail() in c++ properly

后端 未结 3 1402
故里飘歌
故里飘歌 2020-12-09 23:32

I\'m writing a program where I get an integer input from the user with cin>>iUserSel;. If the user puts in a letter, the program goes to an infinite loop.

3条回答
  •  爱一瞬间的悲伤
    2020-12-10 00:10

    The problem you are having is that you don't clear the failbit from the stream. This is done with the clear function.


    On a somewhat related note, you don't really need to use the fail function at all, instead rely of the fact that the input operator function returns the stream, and that streams can be used in boolean conditions, then you could do something like the following (untested) code:

    while (!(std::cin >> iUserSel))
    {
        // Clear errors (like the failbit flag)
        std::cin.clear();
    
        // Throw away the rest of the line
        std::cin.ignore(std::numeric_limits::max(), '\n');
    
        std::cout << "Wrong input, please enter a number: ";
    }
    

提交回复
热议问题