无效输入导致程序崩溃.有没有办法忽略它

Invalid input crashing the program. Is there a way to ignore it?

本文关键字:有没有 崩溃 输入 程序 无效      更新时间:2023-10-16

我的代码旨在允许用户输入一个数字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 ... */
    }
}
相关文章: