使用C数字进行错误检查

Using C isdigit for error checking

本文关键字:错误 检查 数字 使用      更新时间:2023-10-16

对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;
}

调用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"

isdigit(num)为假(因为ASCII的第0位不是数字(,但isdigit(c)为真(因为ASCII第30位有数字"0"(。

isdigit仅检查指定字符是否为数字。一个字符,而不是两个字符,也不是整数,因为num似乎被定义为。由于cin已经为您处理验证,因此您应该完全删除该检查。

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

如果你试图保护自己免受无效输入(范围外、非数字等(的影响,有几个问题需要担心:

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

此处提供更多详细信息:忽略用户输入之外的内容';s从中选择