[英]C++ Number input validation
I need to validate a user input using getch()
only to accept numeric input 我只需要使用getch()
验证用户输入即可接受数字输入
`int input_put=getch();`
if(input >=0 && < 9){
}else{
}
To best accept numeric input, you have to use std::cin.clear() and std::cin.ignore() 为了最好地接受数字输入,必须使用std :: cin.clear()和std :: cin.ignore()
For example, consider this code from the C++ FAQ 例如,请考虑C ++常见问题解答中的以下代码
#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";
...
}
This is by far, the best and the cleanest way of doing it. 到目前为止,这是最好,最干净的方法。 You can also add a range checker easily. 您还可以轻松添加范围检查器。
if(input >= '0' && input <= '9')
要么:
if(isdigit(input))
getch
returns a character code . getch
返回一个字符代码 。 The character code for "0" is 48, not 0, although you can get away with using a character constant instead (since char constants are really integer constants) and that will be more readable. “ 0”的字符代码为48,而不是0,尽管您可以改用字符常量(因为char常量实际上是整数常量),但可读性更高。 So: 所以:
if (input >= '0' && input <= '9')
If you're using Visual C++ (as your tags indicate), you may find the MSDN docs useful. 如果您使用的是Visual C ++(如标签所示),则可能会发现MSDN文档很有用。 For instance, you probably should be using _getch
instead, or _getchw
if you want to write software that can be used more globally. 例如,您可能应该改用_getch
或_getchw
如果要编写可以在全球范围内使用的软件)。 And in that same vein, you probably want to look at isdigit
, isdigitw
, and the like . 同样,您可能希望查看isdigit
, isdigitw
等 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.