我正在(重新)学习编程,我从 C 开始。我的 IDE(如果我可以这么说的话)是 Windows7 上的 cygwin(32 位)和 Visual-Studio 2010。我总是使用 gcc (cygwin) 以及 VS2010 编译器编译我编写的代码。我想,我这样做是因为我认为这是一种很好的学习方式。无论如何,我刚刚了解了 fflush(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);