Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printf not printing to screen

Tags:

c

cygwin

stdio

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.

like image 336
user1060986 Avatar asked Jun 01 '13 07:06

user1060986


3 Answers

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 );
like image 144
zsawyer Avatar answered Oct 27 '22 02:10

zsawyer


you can try for disabling the buffering in stdout by using

setbuf(stdout, NULL);
like image 27
Dayal rai Avatar answered Oct 27 '22 00:10

Dayal rai


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

setlinebuf(stdout);
like image 26
thejh Avatar answered Oct 27 '22 01:10

thejh