Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

c - printf not printing to screen

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
" );
scanf( "%d", &i1 );

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

sums = i1 + i2;
printf( "Sum is %d
", 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
" );
fflush( stdout );
scanf( "%d", &i1 );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...