2011-06-30 39 views
1

對int num使用布爾檢查時,此循環不起作用。它後面的線條無法識別。輸入和整數像60,它只是關閉。我使用isdigit錯了嗎?使用C 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; 
} 
+0

num是如何定義的? –

回答

2

當你調用isdigit(num),該num必須有一個字符(0..255或EOF)的ASCII值。

如果它被定義爲int num那麼cin >> num將把它的整數值,而不是字母的ASCII值。

例如:

int num; 
char c; 
cin >> num; // input is "0" 
cin >> c; // input is "0" 

然後isdigit(num)是假的(因爲在地方ASCII的0不是一個數字),但isdigit(c)是真實的(因爲在ASCII的地方30有一個數字 '0')。

1

如果你想保護自己免受無效的輸入(範圍外,非數字等),有幾個陷阱擔心:這裏

// 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) 

更多細節: Ignore user input outside of what's to be chosen from