int is_valid(char *input)
{
int i;
for (i = 0;; i++)
{
// Check for null terminator
if ( ! input[i])
{
printf("stop executing is_valid()");
return 0;
}
// Will be executed for null terminator... o_O
printf("%c isdigit: %d\n", input[i], isdigit(input[i]));
}
return 1;
}
int main()
{
char input[80];
fgets(input, sizeof(input), stdin);
is_valid(input);
return 0;
}
输出:
1 isdigit: 1
0 isdigit: 1
1 isdigit: 1
isdigit: 0 // Why is that here? null terminator after return?!
stop executing is_valid()invalid input!
为什么在返回之前通过
isdigit
处理空终止符? And ..好的,为什么在条件执行之后呢?
最佳答案
为什么在返回之前通过isdigit
处理空终止符?
它不是。对'\n'
读取的fgets
字符执行。
C11-§7.21.7.2
fgets
函数从流指向的n
到stream
指向的数组中读取的字符数最多少于s
指定的字符数。在换行符(保留)或文件结尾之后,不会读取其他字符。在将最后一个字符读入数组后,立即写入空字符。
对于输入
101
里面有
5
个字符101\n\0
\n
当然不是数字。您还需要为
\n
添加条件if (input[i] == '\0' || input[i] == '\n')
{
printf("stop executing is_valid()");
return 0;
}
关于c - 为什么在c中以如此奇怪的顺序执行代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35042658/