我的一个程序中有以下代码段:
char input[LINE_SIZE + 1]; /* +1 for '\0'. */
while(fgets(input, LINE_SIZE, stdin) != NULL)
{
/* Do stuff. */
}
在一个已被删除的问题中,有人向我指出我的代码可能存在错误。我用“+ 1”表示法声明字符串,以使代码更具信息性和可读性(确保我不会忘记考虑 NULL 终止符,因为这曾经是一个问题)。但是,有人告诉我,fgets
的第二个参数应该使用完全相同的大小。我在这里看到其他帖子和我做同样的做法。
我不确定。在 fgets 参数中也不包含“+ 1”是否是一种不好的做法?
最佳答案
7.21.7.2 Thefgets
function
Synopsis
1#include <stdio.h>
char *fgets(char * restrict s, int n, FILE * restrict stream);
Description
2 Thefgets
function reads at most one less than the number of characters specified byn
from the stream pointed to bystream
into the array pointed to bys
. 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.
添加了强调。
如果指定 LINE_SIZE
, 然后 fgets
将读取最多 LINE_SIZE - 1
字符转化为input
, 并将在最后一个输入字符后写入一个 0 终止符。注意 fgets
如果有空间,将存储换行符。
关于c - fgets 应该使用什么大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42404627/