c - 为什么在c中以如此奇怪的顺序执行代码?

标签 c fgets

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函数从流指向的nstream指向的数组中读取的字符数最多少于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/

相关文章:

c - 如何将网格传递给 "void my_func(void *args)"

c - 在 C 中搜索 .txt 文件中的字符串?

c - 不按回车键获取单个字符

linux - 我怎样才能安全而简单地从文件或标准输入中读取一行文本?

c - 我需要将一个文件(现在是文本文件)拆分为多个缓冲区 C

c - 增加结构成员

c - 我如何修改线程以打印 "hello world again"?在C中

c - 使用 zlib 进行内存解压

c - 来自 ALSA 的 pcm_min.c 示例的警告/错误。可能的问题?

c - 逐行读入链表