2

int num のブール値チェックを使用している間、このループは機能しません。それ以降の行は認識されません。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;
}
4

3 に答える 3

3

を呼び出す場合isdigit(num)numには文字の ASCII 値 (0..255 または EOF) が必要です。

int num次のように定義されている場合cin >> num、文字の ASCII 値ではなく、数値の整数値が入力されます。

例えば:

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

thenisdigit(num)は false (ASCII の 0 桁目は数字ではないため) ですが、isdigit(c)true (ASCII の 30 桁目は数字 '0' であるため) です。

于 2011-06-30T00:06:53.737 に答える
3

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

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

于 2011-06-30T00:06:57.120 に答える
2

無効な入力(範囲外、数値以外など)から身を守ろうとしている場合は、次の点について心配する必要があります。

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

詳細はこちら: 選択対象以外のユーザー入力を無視する

于 2011-06-30T00:46:08.123 に答える