我只是试图编写一个从cin读取的简单程序,然后验证输入是否为整数。如果是这样,我将退出while循环。如果没有,我将再次要求用户输入。
我的程序可以编译并正常运行,这很棒。但是,如果我输入非数字值,它不会提示您输入新的内容。是什么赋予了?
#include <iostream>
using namespace std;
int main() {
bool flag = true;
int input;
while(flag){
try{
cout << "Please enter an integral value \n";
cin >> input;
if (!( input % 1 ) || input == 0){ break; }
}
catch (exception& e)
{ cout << "Please enter an integral value";
flag = true;}
}
cout << input;
return 0;
}
除非您通过告诉C ++ iostream,否则它们不会使用异常cin.exceptions( /* conditions for exception */ )
。
但是您的代码流毫无例外地更加自然。只是做if (!(cin >> input))
,等等。
还请记住在再次尝试之前清除故障位。
整个事情可以是:
int main()
{
int input;
do {
cout << "Please enter an integral value \n";
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
} while(!(cin >> input));
cout << input;
return 0;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句