[英]Why isn't the Isdigit function working properly?
I wrote this short code to test my understanding of the isdigit
function: 我写了这段简短的代码来测试我对
isdigit
函数的理解:
int inChar;
printf("enter input:");
scanf(" %d", &inChar);
if (isdigit(inChar))
printf("Your input was a number");
else
printf("Your input was not a number.\n");
When I test this program and I enter a number, C returns the else statement (Your input was not a number.). 当我测试该程序并输入数字时,C返回else语句(您的输入不是数字。)。 So regardless of if I enter a number or a letter, the program returns the else statement.
因此,无论我输入数字还是字母,程序都会返回else语句。
Why is this so? 为什么会这样呢?
isdigit()
checks if a single character that was passed to it by converting the char value an unsigned char
. isdigit()
通过将char值转换为unsigned char
来检查传递给它的单个字符 。 So, you can't directly pass any int value and expect it to work. 因此,您不能直接传递任何int值并期望它起作用。
Man isdigit()
says: 人
isdigit()
说:
isdigit()
checks for a digit (0 through 9).
To check single digit, you can modify: 要检查一位数字,可以修改:
char inChar;
printf("enter input:");
scanf(" %c", &inChar);
if (isdigit((unsigned char)inChar)) {
printf("Your input was a number");
}
else {
printf("Your input was not a number.\n");
}
If you have an array (a string containing a number) then you can use a loop. 如果有数组(包含数字的字符串),则可以使用循环。
The function's purpose is to classify characters (like '3'
). 该函数的目的是对字符进行分类(例如
'3'
)。 Running it on something that's read using %d
doesn't make sense. 在使用
%d
读取的内容上运行它没有任何意义。
You should read a single char
using %c
. 您应该使用
%c
读取一个char
。 Remember to check that reading succeeded. 记住要检查阅读是否成功。
The C library function void isdigit(int c)
checks if the passed character is a decimal digit character. C库函数void
isdigit(int c)
检查所传递的字符是否为十进制数字字符。
If you badly wanna try it with an int
you can init in this way 如果您非常想尝试使用
int
尝试,则可以通过这种方式进行初始化
int inChar = '2';
The following code gave expected results. 以下代码给出了预期的结果。
int main()
{
char inChar;
printf("enter input:");
scanf(" %c", &inChar);
if (isdigit(inChar))
printf("Your input was a number. \n");
else
printf("Your input was not a number.\n");
return 0;
}
Output: 输出:
vinay-1> ./a.out
enter input:1
Your input was a number
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.