c++ - 按下输入键且没有用户输入时捕获异常
问题描述
我有这段代码要求用户输入并期望一个int。但有时,用户可能会忘记输入或输入错误并按下回车键而不输入任何内容,导致我的程序因以下错误而终止:
terminate called after throwing an instance of 'std::invalid_argument'
what(): stoi
我有一个函数可以检查我的输入是否为 int 并在异常发生时捕获该异常,同时忽略该输入。我正在寻找一种类似的方法来捕获这个无输入错误:捕获异常并忽略它,而不是终止我的程序。
这是我的代码:
int choice;
string theInput;
getline(cin, theInput);
while(cin.fail() || cin.eof() || theInput.find_first_not_of("0123456789") != string::npos) {
// checks if input is a number
cout << "Error: input not a number" << endl;
if( theInput.find_first_not_of("0123456789") == string::npos) {
cin.clear();
cin.ignore(256,'\n');
}
system("CLS");
}
string::size_type st;
choice = stoi(theInput,&st);
感谢:D
解决方案
推荐阅读
- python - 传递一个列表作为输入
- react-native - Lottie Splash Screen with Expo - 带有 Expo 的动画闪屏
- css - 为什么 Sass 编译器会返回带有“根样式表”的错误
- python - Python webscraping - 搜索 EAN 的谷歌结果(13 个字母的数字)
- swift - 从表单选择器中选择 CoreData 实体
- html - 如何在 CSS 中居中其父高度的 90% 的图像
- javascript - 如何处理用户同时尝试填充 Firebase 实时数据库中的有限“插槽”
- python - 如何在 python 中保留零进行计算?
- flutter - 如何在不使用包的情况下在 Flutter 中只检查一个复选框
- android - 如何跟踪我的网站中的迷你信息栏横幅安装?(related_applications)