[英]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
如果要編寫可以在全球范圍內使用的軟件)。 同樣,您可能希望查看isdigit
, isdigitw
等 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.