c++ - fflush(stdin) 的替代方案?

标签 c++

C++ 中真的需要 fflush(stdin) 吗?以这种方式刷新缓冲区中的换行符好吗?

最佳答案

fflush(stdin) 的调用在 C 语言(以及 C++ 语言)中是未定义的行为。

C 语言标准,ISO 9899:1999 在 7.19.5.2/2

中声明

If stream 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

要丢弃整个输入直到下一行,在 C++ 中,最稳健的方法是

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

关于“一闪而过”的程序,你是不是在Windows平台上执行控制台应用程序?此类应用程序最好从控制台窗口执行(开始->运行->cmd.exe)

关于c++ - fflush(stdin) 的替代方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5810410/

相关文章:

c++ - 为什么在我使用模板时 VS 不自动完成?

c++ - 在 QNX Momentics 中为自定义构建配置定义自定义符号

c++ - 延迟功能如何工作?

c++ - 为什么我的代码在阶乘返回垃圾值中查找尾随零的数量

c++ - 如何从路径中获取文件名的词干?

c++ - 读写竞争条件会改变同时读取和写入的数据吗?

C++ 视频处理

c++ - 如果我有 X 的质因数分解,我怎样才能有效地得到一个范围内 X 的所有除数?

c++ - 如何获得有向图上给定顶点的输入边?

c++ - 为什么在 C++ 中使用内联函数不会增加二进制大小?