你能阻止为整数输入的字母吗?

时间:2013-03-03 10:53:14

标签: c++

我想知道是否有任何阻止输入整数的字母。这是我在int main中使用的代码。

do
{
    cout << "Player 1 please enter the value of the row you would like to take ";
    cin >> row;
}while (row != 0 && row != 1 && row != 2 && row != 3);

我对此代码的问题是,如果用户输入一个字母,它会创建一个永无止境的循环。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:4)

标准库不提供任何可以过滤通过标准输入输入的字符的内容。我相信你可以使用像curses这样的库来做到这一点。

但是,您可以做的是检查输入是否成功。 operator>>的{​​{1}}会将流的状态设置为int,如果它无法提取整数(例如,当它遇到failbit或类似的情况时。您可以在布尔上下文中使用提取运算符,如下所示:

'a'

请注意,如果您输入例如cout << "Player 1 please enter the value of the row you would like to take "; while (!(cin >> row) || (row < 0 || row > 3)) { cout << "Invalid input, try again!\n"; // clear the error flags and discard the contents, // so we can try again cin.clear(); cin.ignore(std:numeric_limits<std::streamsize>::max(), '\n'); } ,则读取将成功阅读1abc并将1保留在流中。这可能不是理想的行为。如果您希望将其视为错误,您可以说

abc

并采取相应的行动,或者只是在你获得价值后无条件地忽略流中的所有内容。

答案 1 :(得分:1)

一次获取一个字符,只将数字字符添加到字符串中。使用

cin.get();

循环。

相关问题