【问题标题】:C++ continue statement leading to infinite loopC++ continue 语句导致无限循环
【发布时间】:2015-01-11 12:01:56
【问题描述】:

我目前正在这里编写一段相当基本的代码。我正在尝试检查用户的输入,以便如果它不是请求的数字,则会弹出错误消息并请求新的输入。我正在使用一个 while 循环,当遇到 continue 语句时应该重置它,但是如果输入无效,它总是会陷入无限循环,重复错误消息。任何帮助将不胜感激,谢谢!

 while (tester != 1){
  cout << "Enter your answer: ";
  cin >> userInput;
  if (cin.fail()){                     //check if user input is valid

   cout << "Error: that is not a valid integer.\n";
   continue;  //continue skips to top of loop if user input is invalid, allowing another attempt
  } else{
     tester = 1;     //Tester variable allows loop to end when good value input
  }
}

【问题讨论】:

标签: c++ loops while-loop infinite-loop continue


【解决方案1】:

您需要在失败后清除输入缓冲区。

如果cin &gt;&gt; something 失败,它不会消耗输入流中的“错误”数据,并且下次您返回获取更多时,它将读取相同错误数据。

它会继续这样做,直到奶牛回家,就像我奶奶过去常说的那样 - 不要问我这是什么意思,我很确定她没有花很多钱她的时间清醒:-)

您可以通过以下方式消费到行尾:

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

这是一个完整的程序,展示了它的实际效果:

#include <iostream>
#include <limits>

int main() {
  int userInput, tester = 0;
  while (tester != 1){
    std::cout << "Enter your answer: ";
    std::cin >> userInput;
    if (std::cin.fail()) {
      std::cout << "Not a valid integer.\n";
      std::cin.clear();
      std::cin.ignore(
        std::numeric_limits<std::streamsize>::max(),
        '\n');
      continue;
    } else {
      tester = 1;
    }
  }
  return 0;
}

注意特别是的使用

std::numeric_limits<std::streamsize>::max()

作为长度,这意味着没有强制执行限制。很多人会在这种情况下使用INT_MAX,但这是一回事。

这在实践中不太重要,因为INT_MAX 是一个非常大的数字,您可能会在忽略那么多字符之前遇到行尾,但最好使用正确的值来保证行为。

【讨论】:

  • +1 正要写出完全相同的答案。打败我大声笑
  • @user3189142:你奶奶也有类似的特征?太棒了:-)
  • 嗯,几乎一样。减去奶奶部分
【解决方案2】:

您需要清除失败标志,通常还需要跳过下一个换行符。

这通常是这样做的:

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

【讨论】:

    猜你喜欢
    • 2013-08-26
    • 1970-01-01
    • 2019-06-18
    • 2023-03-18
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    • 2015-12-27
    • 1970-01-01
    相关资源
    最近更新 更多