C ++数字输入验证 [英] C++ Number input validation
问题描述
我需要使用 getch()
验证用户输入只接受数字输入
I need to validate a user input using getch()
only to accept numeric input
`int input_put=getch();`
if(input >=0 && < 9){
}else{
}
推荐答案
getch
返回字符 。 0的字符代码是48,而不是0,虽然你可以使用字符常数而不是(因为char常量是真正的整数常量),并且将更加可读。所以:
getch
returns a character code. 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. So:
if (input >= '0' && input <= '9')
如果您使用的是Visual C ++(如您的标签所示),您可能会发现 MSDN文档有用。例如,你可能应该使用 _getch
,或 _getchw
如果你想编写可以使用更多的软件全球。同样,你可能想看一下 isdigit
, isdigitw
等。
If you're using Visual C++ (as your tags indicate), you may find the MSDN docs useful. For instance, you probably should be using _getch
instead, or _getchw
if you want to write software that can be used more globally. And in that same vein, you probably want to look at isdigit
, isdigitw
, and the like.
这篇关于C ++数字输入验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!