fflush,关于fflush(stdin)清空输入缓存流~VC6与gcc的区别~

1. 为什么 fflush(stdin) 是错的?
首先请看以下程序:
#include
int main( void )
{
int i;
for (;;)
{
fputs("Please input an integer: ", stdout);
scanf("%d", &i);
printf("%d\n", i);
}
return 0;
}
这个程序首先会提示用户输入一个整数,然后等待用户输入,如果用户输入的是整数,
程序会输出刚才输入的整数,并且再次提示用户输入一个整数,然后等待用户 输入。
但是一旦用户输入的不是整数(如小数或者字母),假设 scanf 函数最后一次得到的整数是 2 ,
那么程序会不停地输出"Please input an integer: 2"。
这是因为 scanf("%d", &i); 只能接受整数,如果用户输入了字母,则这个字母会遗留在"输入缓冲区"中。
因为缓冲中有数据,故而 scanf 函数不会等待用户输入,直接就去缓冲中读取,可是缓冲中的却是字母,
这个字母再次被遗留在缓冲中,如此反复,从而导致不停地输出"Please input an integer: 2"。
也许有人会说:"居然这样,那么在 scanf 函数后面加上'fflush(stdin);',把输入缓冲清空掉不就行了?"
然而这是错的!
C和C++的标准里从来没有定义过 fflush(stdin)。
也许有人会说:"可是我用 fflush(stdin) 解决了这个问题,你怎么能说是错的呢?"
的确,某些编译器(如VC6)支持用 fflush(stdin) 来清空输入缓冲,
但是并非所有编译器都要支持这个功能(linux 下的 gcc 就不支持),
因为标准中根本没有定义 fflush(stdin)。
MSDN 文档里 也清楚地写着
fflush _disibledevent=> /* 使用 scanf("%*[^\n]"); 也可以清空输入流, */
/* 不过会残留 \n 字符。 */
printf("%d\n", i);
}
return 0;
}

/* C++ 版本 */
#include
#include // 为了使用numeric_limits

using std::cout;
using std::endl;
using std::cin;
using std::numeric_limits;
using std::streamsize;

int main()
{
int value;
for ( ; ; )
{
cout << "Enter an integer: ";
cin >> value;
if ( cin.eof() || cin.bad() )
{ // 如果用户输入文件结束标志(或文件已被读完),
// 或者发生读写错误,则退出循环
// do something
break;
}
// 读到非法字符后,输入流将处于出错状态,
// 为了继续获取输入,首先要调用 clear 函数
// 来清除输入流的错误标记,然后才能调用
// ignore 函数来清除输入流中的数据。
cin.clear();
// numeric_limits::max() 返回输入缓冲的大小。
// ignore 函数在此将把输入流中的数据清空。
// 这两个函数的具体用法请读者自行查询。
cin.ignore( numeric_limits::max(), '\n' );
cout << value << '\n';
}
return 0;
}
参考资料:
ISO/IEC 9899:1999 (E) Programming languages— C 7.19.5.2 The fflush function
The C Programming Language 2nd Edition By Kernighan & Ritchie
ISO/IEC 14882(1998-9-01)Programming languages — C++
本文版权归 蚂蚁的 C/C++ 标准编程 以及 作者 antigloss 共同所有,转载请注明原作者和出处。谢谢。
http://bbs.linuxtone.org/thread-112-1-1.html
Tags:  stdin fflush函数 fflush

延伸阅读

最新评论

发表评论