我正在对我的 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
}
最佳答案
为什么要向 isalpha
传递一个 float ?将字符存储在 float 中并检查它有什么意义?
isalpha
的声明为 int isalpha ( int c );
,因此如果向其传递一个 float ,该 float 将被截断为 int
,使其产生错误的结果。尝试输入 99.5 或类似的东西,然后看看
更重要的是,isalpha
仅适用于 char 值或 EOF,其他值将调用未定义的行为
The behavior is undefined if the value of ch is not representable as unsigned char and is not equal to EOF.
这本质上是一个 XY 问题。 isalpha 不是验证输入值的方法。您需要以字符串形式获取输入并检查它是否符合您的条件
关于c - isalpha() 返回浮点/整数输入的非零值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22239176/