在我看来,如果输入不是整数,循环将开始,并等待用户的下一个输入。但是,以下代码以“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
读取任何内容。
你必须:
- 调用
cin.clear()
清除错误状态,并且 - 调用
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/