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

后端 未结 4 1976
长情又很酷
长情又很酷 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:14

    Well you always will have an infinite loop, but I know what you really want to know is why cin doesn't keep prompting for input on each loop iteration causing your infinite loop to freerun.

    The reason is because cin fails in the situation you describe and won't read any more input into those variables. By giving cin bad input, cin gets in the fail state and stops prompting the command line for input causing the loop to free run.

    For simple validation, you can try to use cin to validate your inputs by checking whether cin is in the fail state. When fail occurs clear the fail state and force the stream to throw away the bad input. This returns cin to normal operation so you can prompt for more input.

      if (cin.fail())
      {
         cout << "ERROR -- You did not enter an integer";
    
         // get rid of failure state
         cin.clear(); 
    
         // From Eric's answer (thanks Eric)
         // discard 'bad' character(s) 
         cin.ignore(std::numeric_limits::max(), '\n');
    
      }
    

    For more sophisticated validation, you may wish to read into a string first and do more sophisticated checks on the string to make sure it matches what you expect.

提交回复
热议问题