How come fflush(stdin) function is not working?

别说谁变了你拦得住时间么 提交于 2019-12-20 06:31:38

问题


My main question is why is it that the fflush(stdin); function not working? Whenever I run the the code, I am not able to get the second input with space ex. Hello World but instead I get Hello?? thanks

#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();   
}

回答1:


Because fflush(stdin) is undefined behavior. fflush() is only defined by the C standard for output streams, and update streams where the last operation was an output.




回答2:


If you get any output at all, it would be because the code you have displayed in the problem description area, is not the code you are actually using.

Regarding your statement:
I am not able to get the second input with space ex. Hello World but instead I get Hello??.
Without the additional parameter in the printf() statement, you will get no output, and a runtime error.

The line (both places) printf("The word you entered was >>%s<<\n"); needs another parameter, add ,string, like this:

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

That will fix your problem.

Here is output after adding the parameter string in printf() (and not removing fflush())


Apparently, fflush(stdin); is not really the issue here, at least for stated problem?

来源:https://stackoverflow.com/questions/19610319/how-come-fflushstdin-function-is-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!