Question

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();   
}
Was it helpful?

Solution

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.

OTHER TIPS

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())
enter image description here
Apparently, fflush(stdin); is not really the issue here, at least for stated problem?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top