关于scanf和fflush

在C语言的书籍中常常看到scanf()的一下写法:

 
  
  1. scanf("%d",&hoge);

scanf不是以行单位对输入内容进行解释,而是对连续的字符流进行解释(包含换行)。scanf()连续地从流中读入字符,并且对和格式说明(%d)想匹配的的部分进行变换处理。

例如,格式说明符为%d时,输入

123↵

此时,从流中取得123,但是↵依然残留在输入流中,可能会被后面的过程吞掉,造成不想要的结果。

例如:

 
  
  1. #include <stdio.h>
  2. int main(void)
  3. {
  4. int hoge;
  5. char buf[256];
  6. printf("&hoge...%p\n",&hoge);
  7. printf("Input intitial value.\n");
  8. // fgets(buf,sizeof(buf),stdin);
  9. // sscanf(buf,"%d",&hoge);
  10. scanf("%d",&hoge); //如果使用scanf则后面的getchar()会吞掉结束的回车符
  11. fflush(stdin);
  12. for(;;)
  13. {
  14. printf("hoge..%d",hoge);
  15. getchar();
  16. hoge++;
  17. }
  18. return 0;
  19. }

这里第一个getchar()将会吞掉↵。

此外scanf()在读入的过程中,成功转换为几个字符就返回几。

例如

 
  
  1. while (scanf("%d", &hoge) != 1) {
  2. printf("输入错误,请再次输入!");
  3. }

上面的例子也不能用fflush(stdin)来处理虽然能得到一样的结果,但是在其他的平台上却会得到不确定的结果。因为fflush()是对输出流使用的而不是对输入流使用的。C++标准中是这样描述的:


int fflush(FILE *stream);

If stream points to an output stream or an update stream in which
the most recent operation was not input, the fflush function causes
any unwritten data for that stream to be delivered to the host environment
to be written to the file; otherwise, the behavior is undefined.


参考文献:

《征服C指针》

C++ referrence:http://www.cplusplus.com/reference/cstdio/fflush/

 



转载于:https://www.cnblogs.com/bugtan/p/4509819.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值