我需要getch()仅使用接受数字输入来验证用户输入
`int input_put=getch();`
if(input >=0 && < 9){
}else{
}
Run Code Online (Sandbox Code Playgroud)
为了最好地接受数字输入,你必须使用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";
...
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,这是最好和最干净的方式.您还可以轻松添加范围检查器.
完整的代码在这里.
| 归档时间: |
|
| 查看次数: |
2535 次 |
| 最近记录: |