c - fflush(stdin) 不能在 cygwin 中用 gcc 编译,但可以用 visual studio 2010 编译

标签 c visual-studio-2010 cygwin fflush

我正在(重新)学习编程,我从 C 开始。我的 IDE(如果我可以这么说)是 Windows7 上的 cygwin(32 位)和 Visual-Studio 2010。 我总是编译我用 gcc (cygwin) 和 VS2010 编译器编写的代码。我想,我这样做是因为我认为这是一种很好的学习方式。 无论如何,我刚刚了解了 fflush(stdin),即刷新 stdin 缓冲区。似乎是一个很好的功能,否则,使用 scanf 似乎很痛苦。 所以我根据教科书中的一个例子写了下面的代码。它既可以用 cygwin 中的 gcc 编译,也可以用 VS2010 编译。当我运行 VS 编译程序时,它工作正常(s.below),当我在 cygwin 中运行 gcc 编译程序时,fflush(stdin) 不会刷新 stdin 缓冲区(s.below)。 我读过一些关于 fflush(stdin) 在某些情况下具有未定义行为的线程。不管那是什么意思,我都是从 C for Linux Programming 教科书中摘录的。如果 fflush(stdin) 不是清除标准输入缓冲区中内容的有效方法,还有什么其他标准方法?

非常感谢您的回答!

==Windows下运行的程序:

enter a long integer and a double
23.00 78.99
lint = 23
dt = 0.00

enter a five digits input
78493
u entered 78 and 493

==程序在Cygwin中运行:

enter a long integer and a double
23.00 78.99
lint = 23
dt = 0.00

enter a five digits input
u entered 78 and 2665720

==代码====

long lint;
double dt;
int fp, sp;
char fn[50], ln[50];

/* using the l modifier to enter long integers and doubles */
puts ("enter a long integer and a double");
scanf("%ld %lf", &lint, &dt);

printf("lint = %d\ndt = %.2f\n", lint, dt);

fflush(stdin); /*DOES NOT WORK UNDER CYGWIN!?*/

/* use field width to split input */

puts("\nenter a five digits input");
scanf("%2d %3d", &fp, &sp);

printf("u entered %d and %d\n", fp, sp);

最佳答案

7.21.5.2.2 的 C11 说(强调我的):

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.

这意味着您不应该在输入流上调用 fflush(除非您正在为定义了行为的非常特定的操作系统和库编写代码)

这是有充分理由的!您通常会认为 fflush(stdin) 会刷新您刚刚输入的行,对吧?好吧,还有更多。想象一下这样运行你的程序:

$ ./program < input_file

在这种情况下,理论上所有文件都已经在stdin 的缓冲区中。因此,刷新该缓冲区等于结束您的输入,这是一个非常无用的操作。由于这些原因,fflush 不能对输入流有非常明智的行为,这就是它在输入流上未定义的原因。


如果你想忽略当前行,有更好的方法。一个例子如下:

void flush_line(FILE *fin)
{
    int c;
    do
    {
        c = fgetc(fin);
    } while (c != '\n' && c != EOF);
}

这会逐个字符地读取输入并停止,直到发生文件末尾、读取错误或行尾。

关于c - fflush(stdin) 不能在 cygwin 中用 gcc 编译,但可以用 visual studio 2010 编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20081062/

相关文章:

c++ - C/C++ 中的快速字符串标记化

c - 调用 setvbuf 的段错误

Shell命令将大文件拆分为10个小文件

C 字符指针

c - 在字符串中查找字符,然后在该字符之前插入字符

c - 核心产生分段故障

openssl - 为什么在 NetBurner 交叉编译时 GCC 找不到 openssl header ?

c - 在 C 中的宏预处理中生成标签

c++ - VS2010 中的 M_PI : working in Debug conf but not in Release

c# - 无法在 Visual C# 2010 Express 中访问构建配置管理器或构建配置