C语言中fflush(stdin)的作用.docxVIP

  • 4
  • 0
  • 约2.94千字
  • 约 5页
  • 2021-02-06 发布于天津
  • 举报
C/C++ 误区二:fflush(stdi n) 来源:蚂蚁的C/C++ 标准编程 作者:an tigloss 等级:精品 发布于2005-10-22 13:56 被读9885次 【字体:大 中小] google 了一下,发现这个篇文今天看程序时,遇到了 fflush google 了一下,发现这个篇文 章介绍的很详细,贴上来和大家共享一下。 An tigloss 最后修改于 2006-11-25 1. 为什么fflush(stdin) 是错的 首先请看以下程序: #i nclude stdio.h int main( void ) { int i; for (;;) { fputs(Please in put an in teger: , stdout); sca nf(%d, i); prin tf(%d\n, i); } return 0; } 这个程序首先会提示用户输入一个整数,然后等待用户输入,如果用户输入的是整数,程序会输岀 刚才输入的整数,并且再次提示用户输入一个整数,然后等待用户输入。但是一旦用户输入的不是 整数(如小数或者字母),假设 scanf函数最后一次得到的整数是 2,那么程序会不停地输岀 “ Please in put an in teger: 2 。这是因为sea nf(%d, i); 只能接受整数,如果用户输入了字 母,则这个字母会遗留在 输入缓冲区”中。因为缓冲中有数据,故而 scanf函数不会等待用户输 入,直接就去缓冲中读取,可是缓冲中的却是字母,这个字母再次被遗留在缓冲中,如此反复,从 而导致不停地输岀 Please in put an in teger: 2 ”。 也许有人会说: 居然这样,那么在 sca nf函数后面加上’fflush(stdi n);,把输入缓冲清空掉不就 行了? ”然而这是错的! C和C++的标准里从来没有定义过 fflush(stdin) 。也许有人会说: 可是 我用fflush(stdin) 解决了这个问题,你怎么能说是错的呢? ”的确,某些编译器(如 VC6 )支持 用fflush(stdin) 来清空输入缓冲,但是并非所有编译器都要支持这个功能( linux下的gcc就不 支持),因为标准中根本没有定义 fflush(stdi n) 。MSDN 文档里也清楚地写着 fflush on in put stream is an exte nsion to the C sta ndard (fflush 操作输入流是对 C 标准的扩充)。当然, 如果你毫不在乎程序的移植性,用 fflush(stdin) 也没什么大问题。以下是 C99对fflush 函数的 定义: int fflush(FILE *stream); 如果stream 指向输岀流或者更新流(update stream ),并且这个更新流 最近执行的操作不是输入,那么 fflush 函数将把这个流中任何待写数据传送至 宿主环境(host environment )写入文件。否则,它的行为是未定义的。 原文如下: int fflush(FILE *stream); If stream points to an output stream or an update stream in which the most rece nt operati on was not in put, the fflush fun cti on 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. 其中,宿主环境可以理解为操作系统或内核等。 由此可知,如果 stream 指向输入流(如 stdin ),那么fflush 函数的行为是不确定的。故而 使用fflush(stdin) 是不正确的,至少是移植性不好的。 2. 2. 清空输入缓冲区的方法 虽然不可以用fflush(stdi n) ,但是我们可以自己写代码来清空输入缓冲区。只需要在 sea nf函数 后面加上几句简单的代码就可以了。 /* C 版本*/ #i nclude stdio.h int main( void ) { int i, c; for (;;) { fputs(Please in put an in teger: , stdout); sca nf(%d, i); if ( feof(stdin) || ferror(stdin)) TOC \o 1-5 \h \z { /* 如果用户输入文件结束标志(

文档评论(0)

1亿VIP精品文档

相关文档