繁体   English   中英

C ++数字输入验证

[英]C++ Number input validation

我只需要使用getch()验证用户输入即可接受数字输入


`int input_put=getch();`

    if(input >=0 && < 9){ 

}else{


}

为了最好地接受数字输入,必须使用std :: cin.clear()和std :: cin.ignore()

例如,请考虑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";
   ...
 }

到目前为止,这是最好,最干净的方法。 您还可以轻松添加范围检查器。

完整的代码在这里

if(input >= '0' && input <= '9')

要么:

if(isdigit(input))

getch返回一个字符代码 “ 0”的字符代码为48,而不是0,尽管您可以改用字符常量(因为char常量实际上是整数常量),但可读性更高。 所以:

if (input >= '0' && input <= '9')

如果您使用的是Visual C ++(如标签所示),则可能会发现MSDN文档很有用。 例如,您可能应该改用_getch_getchw如果要编写可以在全球范围内使用的软件)。 同样,您可能希望查看isdigitisdigitw

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM