在我看来,如果输入的不是整数,则循环将开始,并等待用户的下一个输入。但是,以下代码以“ 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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句