[英]C++: Checking whether a string character is a digit using isdigit. .
[英]Using C isdigit for error checking
在使用 boolean 檢查 int num 時,此循環不起作用。 go 之后的行無法識別。 輸入 integer 就像 60 一樣,它就關閉了。 我用錯了 isdigit 嗎?
int main()
{
int num;
int loop = -1;
while (loop ==-1)
{
cin >> num;
int ctemp = (num-32) * 5 / 9;
int ftemp = num*9/5 + 32;
if (!isdigit(num)) {
exit(0); // if user enters decimals or letters program closes
}
cout << num << "°F = " << ctemp << "°C" << endl;
cout << num << "°C = " << ftemp << "°F" << endl;
if (num == 1) {
cout << "this is a seperate condition";
} else {
continue; //must not end loop
}
loop = -1;
}
return 0;
}
當您調用isdigit(num)
時, num
必須具有字符的 ASCII 值(0..255 或 EOF)。
如果它被定義為int num
那么cin >> num
會將數字的 integer 值放入其中,而不是字母的 ASCII 值。
例如:
int num;
char c;
cin >> num; // input is "0"
cin >> c; // input is "0"
那么isdigit(num)
為假(因為在 ASCII 的第 0 位不是數字),但isdigit(c)
為真(因為在 ASCII 的第 30 位有一個數字“0”)。
isdigit
僅檢查指定字符是否為數字。 一個字符,不是兩個,也不是 integer,因為num
似乎被定義為。 您應該完全刪除該檢查,因為cin
已經為您處理了驗證。
如果您試圖保護自己免受無效輸入(超出范圍、非數字等)的影響,則需要擔心幾個問題:
// user types "foo" and then "bar" when prompted for input
int num;
std::cin >> num; // nothing is extracted from cin, because "foo" is not a number
std::string str;
std::cint >> str; // extracts "foo" -- not "bar", (the previous extraction failed)
此處有更多詳細信息: 忽略要選擇的內容之外的用戶輸入
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.