当需要数字时键入字符串时,使用cin的无限循环 [英] Infinite loop with cin when typing string while a number is expected

查看:123
本文介绍了当需要数字时键入字符串时,使用cin的无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的循环中,如果我们输入字符作为 cin 输入,而不是预期的数字,那么它会进入无限循环。

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 explain to me why this occurs?

当我们使用 cin 时,如果输入不是数字,那么是否有方法来检测这种情况,以避免上述问题?

When we use cin, if the input is not a number, then are there ways to detect this to avoid abovementioned problems?

unsigned long ul_x1, ul_x2;

while (1)
{
  cin >> ul_x1 >> ul_x2;
  cout << "ux_x1 is " << ul_x1 << endl << "ul_x2 is " << ul_x2 << endl;
}


推荐答案

无限循环,但我知道你真正想知道的是为什么cin不继续提示输入在每个循环迭代导致无限循环自由。

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.

原因是因为cin在你描述的情况下失败,并且不会再读取这些变量的任何输入。通过提供无效的输入,cin进入失败状态,并停止提示输入的命令行

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.

对于简单验证,您可以尝试使用cin通过检查cin是否处于失败状态来验证输入。发生失败时,请清除失败状态,并强制流丢弃错误的输入。这会将cin返回正常操作,因此您可以提示输入更多内容。

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<std::streamsize>::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.

这篇关于当需要数字时键入字符串时,使用cin的无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆