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.

posted @ 2012-10-24 15:03  lymin  阅读(285)  评论(0编辑  收藏  举报