std::cin doesn#39;t throw an exception on bad input(std::cin 不会在错误输入时引发异常)
问题描述
我只是想写一个简单的程序,从cin读取,然后验证输入是一个整数.如果是这样,我将跳出我的 while 循环.如果没有,我会再次要求用户输入.
I am just trying to write a simple program that reads from cin, then validates that the input is an integer. If it does, I will break out of my while loop. If not, I will ask the user for input again.
我的程序编译并运行得很好,这很棒.但是如果我输入一个非数值,它不会提示输入新的内容.什么给?
My program compiles and runs just fine, which is great. But it doesn't prompt for new input if I enter a non numeric value. What gives?
#include <iostream>
using namespace std;
int main() {
bool flag = true;
int input;
while(flag){
try{
cout << "Please enter an integral value
";
cin >> input;
if (!( input % 1 ) || input == 0){ break; }
}
catch (exception& e)
{ cout << "Please enter an integral value";
flag = true;}
}
cout << input;
return 0;
}
推荐答案
C++ iostreams 不使用异常,除非你告诉他们使用 cin.exceptions(/* 异常条件 */).
C++ iostreams don't use exceptions unless you tell them to, with cin.exceptions( /* conditions for exception */ ).
但是您的代码流更自然,无一例外.只需执行 if (!(cin >> input)) 等
But your code flow is more natural without the exception. Just do if (!(cin >> input)), etc.
还要记得在重试之前清除失败位.
Also remember to clear the failure bit before trying again.
整个事情可以是:
int main()
{
int input;
do {
cout << "Please enter an integral value
";
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '
');
} while(!(cin >> input));
cout << input;
return 0;
}
这篇关于std::cin 不会在错误输入时引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:std::cin 不会在错误输入时引发异常
基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
