在需要数字的情况下键入字符串时使用 cin 进行无

Infinite loop with cin when typing string while a number is expected(在需要数字的情况下键入字符串时使用 cin 进行无限循环)

本文介绍了在需要数字的情况下键入字符串时使用 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 错误输入,cin 进入 fail 状态 并停止提示命令行输入导致循环自由运行.

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(), '
');

  }

对于更复杂的验证,您可能希望先读入一个字符串,然后对该字符串进行更复杂的检查,以确保它符合您的预期.

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 进行无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在需要数字的情况下键入字符串时使用 cin 进行无

基础教程推荐