fflush()和清除缓冲区

本文探讨了fflush函数在输入流中的不适用性,并提供了两种有效的方法来清空输入缓冲区,包括宏定义和内联函数实现。

今天写程序,从标准输入流读入字符,因为缓冲区的问题用了fflush()函数,记得以前用过好像还解决了问题,我想当时可能是凑巧了,vs里面可能这方面的功能定义了,但是今天在gcc中就没有那么幸运了,一开始觉得很奇怪,后来网上查了资料才有了这个大发现:

(1)fflush is defined only for output streams. Since its definition of ``flush'' is to complete the writing of buffered characters (not to discard them), discarding unread input would not be an analogous meaning for fflush on input streams.

There is no standard way to discard unread characters from a stdio input stream, nor would such a way be sufficient unread characters can also accumulate in other, OS-level input buffers.

(2)读入字符时清除缓冲区可以采用while循环将缓冲区里的字符都读出,可以把它写成宏或者内联函数

/*method 1: macro definition of read a character from the stdin and then flush the buffer*/
#define scanf_flush(ch)\
  {int c;\
  if(scanf("%c", ch)!=EOF){while((c=getchar())!='\n'&&c!=EOF);}\
  }

/*method 2: inline function*/
inline
scanf_flush(char* ch)
{
  int c;
  if(scanf("%c", ch)!=EOF)
  {
    while((c = getchar())!='\n'&&c!=EOF);
  }
}

(3)有时可以采取简单的办法,即

scanf(" %c", &ch);

see the space? i believe you know why and when it works.

转载于:https://www.cnblogs.com/lymin/archive/2012/10/24/2737191.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值