2011-06-30 2 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" 

(場所でASCIIの0は数字ではないので)、しかしisdigit(c)が真である、その後isdigit(num)が偽(ASCIIの場所30で桁がありますので、 '0')。

3

isdigitは、指定された文字が数字かどうかを確認するだけです。 numとして定義されているように、1文字は2ではなく、整数ではありません。 cinはすでにあなたの検証を処理しているので、そのチェックを完全に削除する必要があります。

http://www.cplusplus.com/reference/clibrary/cctype/isdigit/

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

関連する問題