我发现当我使用fgets
函数时,如下所示:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char str[10];
fgets(str, 5, stdin);
printf("%s", str);
system("PAUSE");
return 0;
}
如果我输入123456789
,它将输出1234
。这是 4 个字符,而不是我在函数中定义的 5 个字符。第五个角色发生了什么?
编辑:标题已更新
最佳答案
这是因为由于 C 字符串以 NUL 结尾,fgets
会考虑字符串终止符 (\0
),因此如果您传递 5 个字符的缓冲区,它会是安全的。
在你的代码中,你应该这样做:
fgets(str, sizeof(str), stdin);
因为 str
是一个已知大小的数组。
关于c - 程序未读取 fgets() 中定义长度的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40578922/