我需要使用 getch()
来验证用户输入,只接受数字输入
`int input_put=getch();`
if(input >=0 && < 9){
}else{
}
最佳答案
为了最好地接受数字输入,您必须使用 std::cin.clear() 和 std::cin.ignore()
例如,考虑来自 C++ FAQ 的这段代码
#include <iostream>
#include <limits>
int main()
{
int age = 0;
while ((std::cout << "How old are you? ")
&& !(std::cin >> age)) {
std::cout << "That's not a number; ";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
std::cout << "You are " << age << " years old\n";
...
}
这是迄今为止最好、最干净的实现方式。您还可以轻松添加范围检查器。
完整代码为here .
关于C++ 数字输入验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4049549/