无效输入导致程序崩溃.有没有办法忽略它
Invalid input crashing the program. Is there a way to ignore it?
我的代码旨在允许用户输入一个数字0-9并将该数字作为字符串输出。 即 1 = "一"。按 Ctrl + D 退出代码。这里供参考:
#include <iostream>
using namespace std;
#include <stdio.h>
int main(){
int num;
while ( !cin.eof() ) {
cin >> num;
switch(num) {
case 0 :
cout << "zero" << endl;
break;
case 1 :
cout << "one" << endl;
break;
case 2 :
cout << "two" << endl;
break;
case 3 :
cout << "three" << endl;
break;
case 4 :
cout << "four" << endl;
break;
case 5 :
cout << "five" << endl;
break;
case 6 :
cout << "six" << endl;
break;
case 7 :
cout << "seven" << endl;
break;
case 8 :
cout << "eight" << endl;
break;
case 9 :
cout << "nine" << endl;
break;
}
}
return 0;
}
当我输入正确的整数时,代码的行为符合预期。如果输入像 10 这样的两位数整数,代码会忽略它,这很好。但是,如果我输入像"i"、"f"或"cat"这样的非整数,程序会反复发送垃圾邮件"零",并且 Ctrl + D 不再用于结束程序。
为什么会这样?有没有办法设置它,以便输入非整数的行为与输入两位数的整数相同?如果没有,有没有办法只允许 cin 接受整数?谢谢!
在输入无效时,cin >> num
卡住。您需要将流重置为"良好状态"并清除错误的输入。
还建议您在尝试输入后立即检查 EOF。
while ( true ) {
cin >> num;
if ( cin.eof() ) break;
if ( !cin ) {
cerr << "Bad input" << endl;
cin.clear();
cin.ignore();
}
switch(num) {
case /* your code ... */
}
}
相关文章:
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 遇到新行时,有没有办法停止istream_iterator
- 有没有一种方法可以在编译时获得作用域类名
- conan有没有办法导出一个空目录
- 对于C++中使用智能指针的指针算术限制,有没有一种变通方法
- 有没有一种方法可以测量c++程序的运行时内存使用情况
- 有没有一种方法可以使用placement new将堆叠对象分配给分配的内存
- 有没有一种方法可以通过"typedef"为重新定义的基本类型定义特征和强制转换运算符
- 有没有可能有一个只有ADL才能找到的非好友功能
- 有没有办法从非C/C++文件中读取C++原始字符串文字的内容
- 有没有一种"cleaner"的方法可以在指向基的指针向量中找到派生类的第一个实例?
- 有没有办法知道Tracer是否成功地完全连接到了jaegerclientcpp中的jaeger后端服务器
- catch框架有没有办法比较流或文件
- 有没有办法在RCPP程序无法正常工作时阻止RGui崩溃?
- 无效输入导致程序崩溃.有没有办法忽略它
- 有没有办法在考虑到崩溃的情况下同步进程
- 在堆中创建数组时崩溃,并在有/没有shared_ptr的情况下将其删除