关于fgets()函数的一个简单问题

    函数原型:char *fgets(char *restrict s, int n, FILE *restrict stream);    

      description: The fgets() function shall read bytes from stream into the array pointed to by s, until n-1 bytes are read, or a <newline> is read and transferred to s, or an end-of-file condition is encountered. The string is then terminated with a null byte.

 

      在pro*c例子中看到类似这样的代码:

      printf("please input your username:");      
      fgets(username,sizeof(username),stdin);  
      username[strlen(username)-1]='/0'; 

      oracle登陆输入用户名和密码大概类似上面所写,我所奇怪的是上面所示最后一行代码,看fgets()函数描述可知该函数遇到换行符会停止输入并将换行符写入字符串中,然后补'/0',所以该行代码作用是去掉回车符并不奇怪,但是当输入字符数是(sizeof(username)-1)时会怎么样呢?应该也是停止输入,然后补'/0',这样上面的代码就会丢掉一个字符,在windows平台下测试发现确实如此,下面是一个简单的小测试程序:

#include <stdio.h>
#include <string.h>
#define LEN 5
int main(int argc, char **argv)
{
   char buf[LEN];
   fgets((char *)buf, sizeof(buf), stdin);
// buf[strlen((char *)buf)-1] = '/0';
   printf("buf is %s, and its length is %d", buf, strlen(buf));
   return 0;
}

当输入字符串长度小于sizeof(buf)-1时,输入'abc',输出为:

buf is abc

, and its length is 4;                 // 这样字符串含有回车符,有问题

但是输入字符串长度等于sizeof(buf)-1时, 输入'abcd', 输出为:

buf is abc, and its length is 4;      // 直接在最后一个字符处补'/0', 没回车符,是想要的结果

 

    所以利用buf[strlen((char *)buf)-1] = '/0';一句去掉回车符,当输入字符串长度等于sizeof(buf)-1时会丢失一个字符,不过这种情况可能应该可以忽略吧,不过好像也算是一个小小的问题吧。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值