怎么来fflush(stdin)功能不起作用?

时间:2013-10-26 18:27:47

标签: c string scanf fflush

我的主要问题是为什么fflush(stdin);功能不起作用? 每当我运行代码时,我都无法使用空格ex获得第二个输入。你好世界,但我得到你好?谢谢

#include <stdio.h>

main(){

    int      x;
    double   y;
    char     string[100];

     /*

      * string input

      */

     printf("Enter one word: ");
     scanf("%s", string);  // note there is no & before string */
     printf("The word you entered was >>%s<<\n");

     printf("Enter many words: ");
     fflush(stdin); // <---- for some reason this function is not working
     scanf("%[^\n]", string); // read up to a newline (multiple words)

     printf("The text you entered was >>%s<<\n");

     getchar();   
}

2 个答案:

答案 0 :(得分:4)

因为fflush(stdin)是未定义的行为。 fflush()仅由输出流的C标准定义,并且最后一个操作是输出的更新流。

答案 1 :(得分:1)

如果您得到任何输出,那将是因为您在问题描述区域中显示的代码不是您实际使用的代码。

关于你的陈述:
我无法使用空格ex获得第二个输入。你好世界,但我得到你好?
如果没有printf()语句中的附加参数,您将得不到输出和运行时错误。

该行(两个地方)printf("The word you entered was >>%s<<\n");需要另一个参数,添加,string,如下所示:

 printf("The text you entered was >>%s<<\n", string);

这将解决您的问题。

string中添加参数printf()后,

输出 (并且删除{{1} })
enter image description here
显然,fflush()在这里并不是真正的问题,至少对于陈述的问题?