std::cin 不会在错误的输入上引发异常
std::cin doesn't throw an exception on bad input
我只是想写一个简单的程序,从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;
}
不要使用using namespace std;
,而是导入您需要的内容。
最好一次输入一行。如果您在一行中有多个单词,或者在键入任何内容之前按enter键,这将使行为更加直观。
#include <iostream>
#include <sstream>
#include <string>
using std::cerr;
using std::cin;
using std::cout;
using std::endl;
using std::flush;
using std::getline;
using std::istringstream;
using std::string;
int main() {
int input;
while (true)
{
cout << "Please enter an integral value: " << flush;
string line;
if (!getline(cin, line)) {
cerr << "input failed" << endl;
return 1;
}
istringstream line_stream(line);
char extra;
if (line_stream >> input && !(line_stream >> extra))
break;
}
cout << input << endl;
return 0;
}
相关文章:
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 2D数组来自文本输入,中间有空格
- 异常处理:如果用户输入不是三个特定字符之一
- C++中的奇怪异常代码,当用户输入为 23 时,退出值 1,073,740,940(代码:0xc0000374)
- C++:为什么当我想输入"q"退出时,这会给我一个异常抛出错误?
- 推荐一种在未输入获取行分隔符时引发异常的方法?
- 当用户在字符数组中输入整数值时捕获异常
- 使用C++ CGI 脚本输入的异常
- 异常规范和标准输入迭代器
- 当输入应该是 int 时,如何为 char 创建异常
- 输入 main() 之前出现堆栈溢出异常
- 正在捕获输入和输出文件的异常
- 当输入文件夹名称时,流应该引发异常
- std::cin 不会在错误的输入上引发异常
- 用于控制字符串输入的异常类
- 如何为错误输入编写异常处理
- Python输入和异常vs. c++
- 如何:捕获输入函数异常的可变包装函数
- 从二进制文件输入字符串时未处理的异常| VisualStudio
- 排序函数为大输入 0 提供浮点异常