//Checks if it's an integer, other wise halt the program
void checkInt(char s[]){
int i;
boolean boo = TRUE;
fgets(s, sizeof(s), stdin);
for (i = 0; i < strlen(s); ++i){
printf("%d",isdigit(s[i]));
if (!(isdigit(s[i]))){
boo = FALSE;
printf("Invalid input!\n");
printf("CLOSING PROGRAM");
exit(1);
}
printf("Cool");
}
}
int main()
{
int userInput;
scanf("%d", &userInput);
char buf[sizeof(int)*3+2];
snprintf(buf, sizeof buf, "%d", userInput);
checkInt(buf);
return 0;
}
我已经玩了一段时间了,我只是似乎不明白为什么当我在其中传递数字时,我的 isDigit 总是返回 0?我尝试使用在线 Iodeone.com,它按预期工作,但是当我使用编译我的老师希望我们使用的内容时,是数字突然不认识它们是数字
最佳答案
您的代码存在一些问题:
您初始化一个缓冲区以传递给
checkInt()
,但在checkInt()
里面您可以通过调用fgets()
覆盖该缓冲区来忽略该缓冲区中的内容。 ;变量
s
在checkInt()
实际上是一个指针,而不是一个数组,所以sizeof(s)
没有提供您想要的尺寸;fgets()
覆盖传入checkInt()
的数据可能只是读取stdin
中留下的换行符通过scanf()
流调用 - 因此缓冲区基本上被设置为相当于"\n"
的字符串。这就是为什么isdigit()
调用永远不会看到数字。
关于c - isDigit() 一直返回 0,即使它是数字,C 语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26031870/