没有用到fgets()时:
char *a="123456789";
printf("%d\n",strlen(a));
那么输出9,但不包括结束字符(即 null 字符)
用到fgets时
char a[100];
fgets(a,100,stdin);
printf("%ld",strlen(a));
当输入:123456789
那么输出10,原因在于fgets函数,查看fgets系统手册时(在terminal运行man fgets),会看到如下:
fgets() reads in at most one less than size characters from stream and
stores them into the buffer pointed to by s. Reading stops after an
EOF or a newline. If a newline is read, it is stored into the buffer.
A terminating null byte ('\0') is stored after the last character in
the buffer.
翻译过来:
fgets()最多从流中读取小于大小的字符,并将它们存储到s所指向的缓冲区中。在EOF或换行符之后停止读取。如果读取换行符,则将其存储到缓冲区中。终止的空字节(\ 0)存储在缓冲区中的最后一个字符之后。
意味着fgets()函数将读入‘\n’后,会存储进去字符串里面,然后再放'\0',所以输出是10.我们可以用下面的代码来测试一下是否如此呢。
#include<stdio.h>
#include<string.h>
int main(){
char a[100];
fgets(a,100,stdin);
printf("%ld\n",strlen(a));
for(int i=0;i<strlen(a);i++)
{
if(a[i]=='\n')
printf("\\n");
else if(a[i]=='\0')
printf("end");
else
printf("%c",a[i]);
}
printf("\n");
return 0;
}
输入:123456789 结果如下:
由此可以看出,‘\n’会在strlen()函数之中统计出来的。
那使用scanf()函数呢
使用scanf()函数并不会把‘\n’放进去字符串里面去。那么上面输出长度自然是9