0

When I run my program using scanf() none of my prior print statements print (scanf() statement is at end of program after a printf() statement), it is only when I input something that my program will begin to run and print everything out that was initially supposed to be printed before the input was taken (even though nothing will print before hand). I am using the gcc compiler through a gitbash terminal just using input from the terminal (no files or nothing).

When I remove my the scanf() statement from the end of my program the program runs fine and everything prints as it should. Once I put the scanf() statement at the end of my program (after the printf() statements) and run it, nothing will print until I enter some sort of input. My program is essentially:

printf("blah blah blah");
int getInput;
scanf("%d", &getInput);

When I go to terminal and enter gcc filename.c and then ./a to run the executable, the cursor just blinks signifying that the program is running but no print statement is printed. It is only when I enter a number into the terminal and press enter that the print statement is printed to the terminal. I was hoping to have the print statement print before any input is required. I have attached three screenshots to further show my dilemma. Image of the code that I am running Image of what terminal looks like after I compile and run Shows that I must enter input for program to execute

  • 3
    Output is buffered. Add a `fflush(stdout);` before the `scanf`. – Retired Ninja Aug 06 '23 at 02:23
  • Or, add `'\n'` to the end of the printed string has been suggested as a solution, too... (PS: Why are you not handling the value returned from `scanf()`?) – Fe2O3 Aug 06 '23 at 02:25
  • @Gavin Robinson The `scanf()` should flush `stdout`. Unfortunately it does not on your set-up. To cope with this non-compliant behavior, `fflush(stdout)` as mentioned elsewhere. – chux - Reinstate Monica Aug 06 '23 at 05:02
  • @chux: [§7.21.3 ¶3 of the ISO C11 standard](http://port70.net/~nsz/c/c11/n1570.html#7.21.3p3) uses the words `"are intended"` instead of `"shall"`. Also, it states: `"Support for these characteristics is implementation-defined [...]"` My interpretation of this wording is that the "intended" characteristics are not mandatory, so that this does not make the implementation "non-compliant". – Andreas Wenzel Aug 06 '23 at 05:18
  • @AndreasWenzel True that stream flushing has many [implementation defined](https://stackoverflow.com/a/39536803/2410359) attributes and [comment](https://stackoverflow.com/questions/76844212/scanf-making-program-not-run-correctly-in-c?noredirect=1#comment135471471_76844212) overstates. – chux - Reinstate Monica Aug 07 '23 at 02:25

0 Answers0