0

我正在用 C 对我的程序进行一些错误检查,目前正在测试以确保输入数据点是float/ int(基本上不是字符)

为此,我正在使用该isalpha功能。它适用于 100 以下的所有数字,但如果我输入 100 的值,它将返回 1024 而不是 0。发生这种情况的任何特定原因,或者您知道更好的错误检查方法吗?

if ((isalpha(T1) != 0) || (isalpha(T2) != 0) || (isalpha(T3) != 0)
|| (isalpha(X1) != 0) || (isalpha(X2) != 0) || (isalpha(X3) != 0))
{
    error checking statements
}
else
{
    Calculations
}
4

1 回答 1

1

Why do you pass a float to isalpha? What's the point storing a character in a float and checking it?

The declaration for isalpha is int isalpha ( int c );, so if you pass a float to it, the float will be truncated to int, making it produce a wrong result. Try inputting 99.5 or something like that and see

More importantly, isalpha only works with a char value or EOF, other values will invoke undefined behavior

The behavior is undefined if the value of ch is not representable as unsigned char and is not equal to EOF.

http://en.cppreference.com/w/cpp/string/byte/isalpha

This is essentially an XY problem. isalpha is not a way to validate input values. You need to get the input as string and check whether it fits your condition or not

于 2014-03-07T07:07:42.523 回答