2010-10-06 163 views
1

为什么当输入错误输入时无限循环?我该如何纠正?当输入错误输入时无限循环无限循环

int operation; 
    while (true) { 
     cout << "What operation would you like to perform? Enter the number corresponding to the operation you would like to perform. "; 
     cin >> operation; 
     if (operation >= 1 && operation <= 5) break; 
     cout << "Please enter a number from 1 to 5, inclusive.\n"; 
    } 
+0

这看起来与您最近问的问题非常相似。另一个问题发生了什么? – 2010-10-06 19:20:50

+0

啊,发布它的人不一样。这解释了为什么我找不到它! – 2010-10-06 19:30:19

回答

0

如果你有一个cin无法解析的输入,流将处于错误状态。

这里是你如何清除错误状态,则忽略该项输入一个例子:

int operation; 
while (true) { 
cout << "What operation would you like to perform? Enter the number corresponding to the operation you would like to perform. "; 
     cin >> operation; 
     if (cin.fail()) 
     { 
      cout << "Not a number " << endl; 
      cout << "Please enter a number from 1 to 5, inclusive.\n"; 
      cin.clear(); 
      cin.ignore(100, '\n'); 
      cin >> operation; 
     } 
     if (operation >= 1 && operation <= 5) break; 
     cout << "Please enter a number from 1 to 5, inclusive.\n"; 
    } 

注意,它试图忽略不正确的之前清除输入流的错误状态是非常重要的字符。希望有帮助 -

+0

当到达输入结束时,该答案从未初始化的内存中读取,然后进入无限循环。 – 2013-06-24 21:38:07

3

在输入流遇到错误后,流将处于失败状态。您明确地必须清除该流上的故障位并在之后将其清空。尝试:

#include <limits> 
#include <iostream> 

... 
... 
// erroneous input occurs here 

std::cin.clear(); 
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 

您可以检查输入通过检查好()不好(),失败()或EOF的返回值升高()的错误。这些函数只是返回内部状态位的状态(如果设置了相应位,则返回true - 除了good(),显然,如果所有内容都按顺序返回)。

+0

这有效,但是当我输入正确的输入时,我必须按两次输入以接收下一个提示。我如何避免这种情况,所以我只需要输入一次? – idealistikz 2010-10-06 19:28:27

+1

我已经回答说:检查是否发生了错误,*只有*清除流。 – 2010-10-06 19:39:30