使用fflush(stdin) [英] Using fflush(stdin)

查看:157
本文介绍了使用fflush(stdin)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,快速Google搜索 fflush(stdin)清除输入缓冲区会显示大量网站警告使用它。



如何使用 fflush(stdin)

解决方案

简单:这是一个很简单的方法:是未定义的行为,因为 fflush 意味着在输出流上调用。这是C标准的摘录:


int fflush(FILE * ostream);



ostream指向输出流或
更新流,其中未输入最多
最近操作,
fflush函数导致该流的任何未写入的
数据将
传递给主机环境以将
写入文件;否则,行为
未定义。


所以这不是一个多糟的问题。 fflush(stdin)明显错误,而且不得使用


So a quick Google search for fflush(stdin) for clearing the input buffer reveals numerous websites warning against using it. And yet that's exactly how my CS professor taught the class to do it.

How bad is using fflush(stdin)? Should I really abstain from using it, even though my professor is using it and it seems to work flawlessly?

解决方案

Simple: this is undefined behavior, since fflush is meant to be called on an output stream. This is an excerpt from the C standard:

int fflush(FILE *ostream);

ostream 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.

So it's not a question of "how bad" this is. fflush(stdin) is plainly wrong, and you mustn't use it, ever.

这篇关于使用fflush(stdin)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆