10

If I try to run the following simple code under Cygwin on Windows 7,

#include <stdio.h>
int main() {
int i1, i2, sums;

printf( "Enter first integer\n" );
scanf( "%d", &i1 );

printf( "Enter second integer\n" );
scanf( "%d", &i2 );

sums = i1 + i2;
printf( "Sum is %d\n", sums );

return 0;
}

it compiles (via gcc) without a problem, but when I try to execute it, the first statement ("Enter first integer") isn't printed to the terminal, and I have to input two successive numbers (e.g. 3 and 4) before I get,

3
4
Enter first integer
Enter second integer
Sum is 7

Can anyone explain to me what is happening here. This works perfectly well under MinGW.

thejh
  • 44,854
  • 16
  • 96
  • 107
user1060986
  • 141
  • 1
  • 1
  • 3
  • Try to run the application in cygwin's terminal. – akhil Jun 01 '13 at 07:44
  • According to [§7.21.3 ¶3 of the ISO C standard](http://port70.net/~nsz/c/c11/n1570.html#7.21.3p3), the output stream is supposed to be automatically flushed when new input is requested from the operating system. However, this is not strictly required by ISO C. Therefore, this is not a bug in cygwin. It is just not well implemented. – Andreas Wenzel Feb 22 '22 at 23:42
  • 14 hours after this question was posted, [this duplicate question](https://stackoverflow.com/q/16877264/12149471) was posted, which has had significantly more activity. It would probably be appropriate to close one of the questions as a duplicate of the other. However, I am not sure which one should be closed, because one has had more activity, but the other one was asked earlier. – Andreas Wenzel Feb 23 '22 at 00:13

3 Answers3

14

Like @thejh said your stream seems to be buffered. Data is not yet written to the controlled sequence.

Instead of fiddling with the buffer setting you could call fflush after each write to profit from the buffer and still enforce the desired behavior/display explicitly.

printf( "Enter first integer\n" );
fflush( stdout );
scanf( "%d", &i1 );
zsawyer
  • 1,824
  • 17
  • 24
8

you can try for disabling the buffering in stdout by using

setbuf(stdout, NULL);
Dayal rai
  • 6,548
  • 22
  • 29
  • 1
    Question; is this compiler/toolchain dependant or platform dependant? Can it be disabled with a compiler flag? – Andy J Aug 30 '18 at 08:01
2

It seems that the output of your program is buffered. Try enabling line buffering explicitly:

setlinebuf(stdout);
thejh
  • 44,854
  • 16
  • 96
  • 107