1 c++ error-handling visual-studio-2012
我只是想编写一个从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;
}
Run Code Online (Sandbox Code Playgroud)
除非你告诉他们,否则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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2887 次 |
| 最近记录: |