我编写这段短代码是为了测试我对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");
当我测试这个程序并输入一个数字时,C返回else语句(您的输入不是数字)。所以不管我输入的是数字还是字母,程序都会返回else语句。
为什么会这样?
最佳答案
isdigit()
通过将char值转换为unsigned char
来检查传递给它的单个字符。
所以,不能直接传递任何int值并期望它工作。
男人说:
isdigit()
checks for a digit (0 through 9).
要检查单个数字,可以修改:
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");
}
如果有数组(包含数字的字符串),则可以使用循环。