如何避免使用Try-Catch(C++)在整数值中输入字符串
How to avoid Input a String in an Integer value using Try Catch (C++)
我只是希望用户避免使用Try Catch在整数值中输入字符串,因为使用while循环根本不起作用。我知道如何在Java中使用TryCatch,但在C++中我不知道。我一直在尝试这样的东西:
#include <iostream>
using namespace std;
main(){
int opc;
bool aux=true;
do{
try{
cout<<"PLEASE INSERT VALUE:"<<endl;
cin>>opc;
aux=true;
}
catch(int e){
aux=false;
throw e;
cout<<"PLEASE INSERT A VALID OPTION."<<endl;
}
}while(aux==false);
system("PAUSE");
}//main
有更简单、更好的方法可以做到这一点,但如果您真的想要异常,可以启用它们并捕获std::ios_base::failure
。类似这样的东西:
int main() {
int opc;
bool aux = true;
cin.exceptions(std::istream::failbit);
do {
try {
cout << "PLEASE INSERT VALUE:" << endl;
cin >> opc;
aux = true;
}
catch (std::ios_base::failure &fail) {
aux = false;
cout << "PLEASE INSERT A VALID OPTION." << endl;
cin.clear();
std::string tmp;
getline(cin, tmp);
}
} while (aux == false);
system("PAUSE");
}
在正常情况下,当提供的数据不合适时,std::cin作为所有istream不会抛出异常。流将其内部状态更改为false。所以你可以简单地做一些事情:
int n;
std::cin >>n;
if(!std::cin) {
// last read failed either due to I/O error
// EOF. Or the last stream of chars wasn't
// a valid number
std::cout << "This wasn't a number" << std::endl;
}
int opc;
cin >> opc;
当您尝试读取非数字值时,将设置流的坏位。您可以检查流是否处于良好状态。如果没有,请重置状态标志,如果需要,请重试读取。请注意,当设置坏位时,将忽略后面的任何读取。因此,在进行另一次尝试之前,您应该先清除输入流中的坏比特,然后忽略其余的坏输入。
// If the input stream is in good state
if (cin >> opc)
{
cout << opc << endl;
}
else
{
// Clear the bad state
cin.clear();
// Ignore the rest of the line
cin.ignore(numeric_limits<streamsize>::max(), 'n');
}
// Now if the user enters an integer, it'll be read
cin >> opc;
cout << opc << endl;
相关文章:
- C 字符串返回字符串的整数/双精度/长整型值
- 尝试将字符串/字符转换为整数会产生意外结果
- 从字符串中提取整数并形成一个数组
- 如何将整数字符串转换为整数的二维向量?
- 如何初始化整数+字符串数组
- 将字节数组转换为逗号分隔的整数字符串
- 编写 LLVM 整数/字符串输入
- 使用户输入整数字符串,然后输出不同的字符串
- 如何在 python 中将无符号字符类型的整数字符串转换为整数
- 将整数字符串转换为整数的最简单方法
- 如何检查输入是否为整数/字符串
- 如何将二进制字符串转换为整数字符串
- 将二进制字符串转换为整数字符串c++
- 如何在c++中将一个整数字符串转换为数组
- 整数字符串压缩算法
- 当 0 是行中的最后一个整数时,如何使用 c++ 检测您已经到达整数字符串的末尾?
- 将整数字符串解析为 std 向量
- 用空格分割一个正/负整数字符串
- 我如何在c++中排序一个整数字符串
- 添加整数字符串