29

在 C++ 中,如何处理错误的输入?就像,如果程序要求输入一个整数,当你输入一个字符时,它应该能够做一些事情,然后循环重复输入,但是当你输入一个整数时,循环进入无限期,反之亦然。

4

4 回答 4

55

程序进入无限循环的原因std::cin是由于输入失败而设置了错误的输入标志。要做的是清除该标志并丢弃输入缓冲区中的错误输入。

//executes loop if the input fails (e.g., no characters were read)
while (std::cout << "Enter a number" && !(std::cin >> num)) {
    std::cin.clear(); //clear bad input flag
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //discard input
    std::cout << "Invalid input; please re-enter.\n";
}

请参阅C++ FAQ和其他示例,包括在条件中添加最小值和/或最大值。

另一种方法是将输入作为字符串获取,然后使用std::stoi允许检查转换的其他方法将其转换为整数。

于 2012-04-27T11:34:29.053 回答
8

票数最高的答案很好地涵盖了解决方案。

除了那个答案之外,这可能有助于更好地可视化正在发生的事情:

int main()

    int input = 1;//set to 1 for illustrative purposes
    bool cinState = false;
    string test = "\0";
    while(input != -1){//enter -1 to exit
        cout << "Please input (a) character(s): ";//input a character here as a test
        cin >> input; //attempting to input a character to an int variable will cause cin to fail
        cout << "input: " << input << endl;//input has changed from 1 to 0
        cinState = cin;//cin is in bad state, returns false
        cout << "cinState: " << cinState << endl;
        cin.clear();//bad state flag cleared
        cinState = cin;//cin now returns true and will input to a variable
        cout << "cinState: " << cinState << endl;
        cout << "Please enter character(s): ";
        cin >> test;//remaining text in buffer is dumped here. cin will not pause if there is any text left in the buffer.
        cout << "test: " << test << endl;
    }
    return 0;    
}

将缓冲区中的文本转储到变量中并不是特别有用,但它有助于可视化为什么cin.ignore()是必要的。

我还注意到输入变量的更改,因为如果您在while循环条件或 switch 语句中使用输入变量,它可能会陷入死锁,或者它可能会满足您不期望的条件,这可以调试起来更加混乱。

于 2015-01-25T09:24:24.290 回答
-6

测试输入以查看它是否是您的程序所期望的。如果不是,请提醒用户他们提供的输入是不可接受的。

于 2012-04-27T11:36:43.317 回答
-6

如果 ascii 值在 65 到 90 或 97 到 122 之间,您可以通过 ASCII 值检查它是否是字符。

于 2012-04-27T11:40:54.887 回答