c++ - 为什么我的 do while 语句中出现无限循环?

标签 c++ algorithm data-structures

在我看来,如果输入不是整数,循环将开始,并等待用户的下一个输入。但是,以下代码以“value for a”循环,用户没有机会键入其他输入。

#include<iostream>

using namespace std;

int main()
{
        int a;
        do{
                cout <<"Value for a: ";
                cin >>a;
        }
        while(cin.fail());
   return 0;
}

最佳答案

当用户输入错误的输入时,cin 设置错误状态。在清除错误状态之前,您无法从 cin 读取任何内容。

你必须:

  1. 调用 cin.clear() 清除错误状态,并且
  2. 调用 cin.ingore() 忽略该行的其余部分。

您需要以下内容:

do {
   cout <<"Value for a: ";
   if ( cin >> a )
   {
      // Input was successful.
      break;
   }

   // Clear the error state of the input stream.
   cin.clear();

   // Ignore the rest of the line.
   cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
} while (true);

并添加

#include <limits>

能够使用std::numeric_limits

关于c++ - 为什么我的 do while 语句中出现无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33471943/

相关文章:

algorithm - 平衡二叉搜索树也是堆

algorithm - 用递归函数返回

javascript - Javascript 中的对象与数组的键/值对

c++ - 如何在 C++ 中的多个类之间共享一个实例,而不是使用单例模式

c++ - MFC:为什么会发生这种堆损坏? (array_s.cpp/afxcoll.inl)

c++ - std::vector 推速?

c - 求解公式中每个变量的算法

c++ - 为什么我需要在我的子类中重新声明 `virtual` 方法? [C++/多态]

python - 将巨大的三列表转换为表的脚本

performance - 嵌套循环的大 O 运行时间?