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

Can you stop letters being entered for an integer?

本文关键字:输入 整数      更新时间:2023-10-16

我想知道是否有阻止字母输入整数的方法。以下是我在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);

我对这段代码的问题是,如果用户输入一个字母,它会创建一个永无止境的循环。

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

但是,您可以做的是检查输入是否成功。operator>> for 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留在流中。这可能不是理想的行为。如果你想把它当作错误处理,你可以输入

if ((cin >> std::ws).peek() != EOF) { /* there's more input waiting */ }

和相应的操作,或者在获得值后无条件忽略流中的所有内容。

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

cin.get();