strlen()和fgets()搭配使用时的注意要点

没有用到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

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值