scanf() ,getchar(),gets(),fgetc(),fgets(),fscanf()的区别

1.gets()函数

------------------------------------------------------------------

读取整行输入,直至遇见换行符,丢弃换行符,存储其他字符,并在末尾添加空字符使其成为一个c字符串。

经常和puts()一起使用。

/*  getsputs.c  -- using gets() and puts() */
#include <stdio.h>
#include<stdlib.h>
#define STLEN 81
int main(void)
{
char words[STLEN];


puts("Enter a string, please.");
gets(words);  // typical use
printf("Your string twice:\n");
printf("%s\n", words);
puts(words);
puts("Done.");
printf("*******************\n");
system("pause");
return 0;

}




缺点:

gets()只有一个参数,不检查数组空间是否够用,会有缓冲区溢出的情况(buffer overflow),多余的字符占用尚未分配的空间,会导致异常。

2.fgets()函数

------------------------------------------------------------------

/*  fgets1.c  -- using fgets() and fputs() */
#include <stdio.h>
#include<stdlib.h>
#define STLEN 14
int main(void)
{
    char words[STLEN];
    
    puts("Enter a string, please.");
    fgets(words, STLEN, stdin);
    printf("Your string twice (puts(), then fputs()):\n");
    puts(words);
    fputs(words, stdout);


    puts("Enter another string, please.");
    fgets(words, STLEN, stdin);
    printf("Your string twice (puts(), then fputs()):\n");
    puts(words); fputs("###",stdout);
fputs(words, stdout); puts("###");


    puts("Done.");
printf("******************\n");
system("pause");
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值