你能停止为整数输入字母吗?
Can you stop letters being entered for an integer?
我想知道是否有阻止字母输入整数的方法。以下是我在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();
相关文章:
- 如何打印不带空格的输入整数?
- 编写一个程序,输入整数 n 并打印该数字的字符数(符号除外)
- 如何在不中断剩余代码的情况下仅C++中输入整数
- 如何在输入整数时中断 for 循环
- C++ 在 CIN 双精度时挂起,但如果输入整数,则继续
- 我如何使用CIN输入整数,每个数字都被逗号分隔
- 如何输入整数并将其从最高到最低排序
- 如何创建一个程序,用户输入整数并输出90度数字金字塔
- 使用对输入整数的文件输入
- 使用户输入整数字符串,然后输出不同的字符串
- 从 fstream 到 2d 矢量的输入整数<矢量<int>> C++
- 用户输入整数后跟垃圾
- 输入整数直到 C/C++ 中的换行符
- 输入整数的最快方法
- C++循环 - 输入整数,直到用户退出
- 尝试输入整数行并在以矢量作为存储的函数的插入排序类型中排序
- 如何使C++程序在用户输入整数时抛出错误,而需要字符串
- 当要求输入整数并使用isdigit检查时,将char转换为int
- 如何通过指针输入整数数组并打印出数组和数组的大小(C++)
- 如果打印后输入整数,则C++分段故障,但其他情况下可以