Infinite loop with cin when typing string while a number is expected

后端 未结 4 1928
长情又很酷
长情又很酷 2020-11-22 00:35

In the following loop, if we type characters as the cin input instead of numbers which are expected, then it goes into infinite loop. Could anyone please explai

4条回答
  •  攒了一身酷
    2020-11-22 01:17

    Attention

    Please pay attention to the following solution. It is not complete yet to clear the error in your case. You will still get an infinite loop!

    if (cin.fail())
    {
         cout << "Please enter an integer";
         cin.clear();
    }
    

    Complete Solution

    The reason is you need clear the failed state of stream, as well as discard unprocessed characters. Otherwise, the bad character is still there and you still get infinite loops. You can simply can std::cin.ignore() to achieve this. For example,

    if (cin.fail())
    {
             cout << "Please enter an integer";
             // clear error state
             cin.clear();
             // discard 'bad' character(s)
             cin.ignore(std::numeric_limits::max(), '\n');
    }
    

    Another Solution

    You can also use getline and stringstream to achieve. Here is a brief example.

       string input;
       while (1)
       {
          getline(cin, input);
          stringstream(input) >> x;
          cout << x << endl;
       }
    

提交回复
热议问题