while loop to infinity when the input of a cin is a 'dot'

后端 未结 4 2058
执念已碎
执念已碎 2021-01-27 19:22

I am having trouble using the cin method to acquire a variable. When the input is a number there is no problem, but when it is a special character like a dot [.], the whileloop

4条回答
  •  天命终不由人
    2021-01-27 20:02

    This example exactly reproduces your problem:

    #include 
    
    int main()
    {
        int i = 5;
        while (i < 1 || i > 3)
        {
            std::cin >> i;
        }
    }
    

    Here's what happens: When operator>> fails to read an integer (e.g. when you type a dot and press enter), whatever you typed stays in the stream, including the newline character. So in the next iteration of the while loop the next input is already there and since it's not a valid integer, the loop can never break. You need to make sure that, when operator>> fails, you empty the stream and clear all the error flags that got set.

    #include 
    #include 
    
    int main()
    {
        int i = 5;
        while (i < 1 || i > 3)
        {
            if (!(std::cin >> i))
            {
                // clear streams internal error flags
                std::cin.clear();
                // ignore what's left in the stream, up to first newline character
                // or the entire content, whichever comes first
                std::cin.ignore(std::numeric_limits::max(), '\n');
            }
        }
    }
    

提交回复
热议问题