gpt4 book ai didi

c - fgets 之后 Strlen 给出了错误的输出

转载 作者:行者123 更新时间:2023-11-30 20:26:04 25 4
gpt4 key购买 nike

我使用 fgets 读取了一个字符串。它打印正确,但如果我尝试使用 strlen 或一段时间输出长度直到 NULL,它会返回一个错误值。 fgets 不是以 NULL 结束字符串吗?

char word[256];
fgets(word, sizeof(word), stdin);
while(word[i])
i++;
printf("%d",i);

对于字符串 aba,它输出 40。

最佳答案

函数fgets还包括字符串中的换行符。所以函数 strlen 计算这个符号。

来自 C 标准

2 The fgets function reads at most one less than the number of characters specified by n from the stream pointed to by stream into the array pointed to by s. No additional characters are read after a new-line character (which is retained) or after end-of-file. A null character is written immediately after the last character read into the array.

关于c - fgets 之后 Strlen 给出了错误的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26831846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com