Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c - printf not print on the console in eclipse?

#include<stdio.h>

int main() {
    int n, s, i;
    do {
        printf("n= "); // here is the problem ?
        scanf("%d", &n);
    } while (n<100 || n <= 0);
    s = 0;
    i = 0;
    while (i <= n) {
        i = i + 2;
        s = s + i;
    }
    printf("s=%d", s);
    getchar();
    return 0;
}

I ran it in eclipse c/c++ and it not print "n=" first. But when I run it in another IDE like DEV-C++ or VS 2017, it run well. When add this line after printf and I ran like I expected.

fflush(stdout);

What is the problem here ?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

printf doesn't print to screen unless buffer is flushed

Looks like your streams are buffered. Data you write to stdout and other streams is buffered and all output once you flush your buffer. This allows for better performance as IO is slowest among all your CPU operations.

At this point, you have at least these options:

  1. Explicitly flush the buffer by calling fflush( stdout ) every time you use printf
  2. Disable buffering setbuf(stdout, NULL);
  3. Flush buffer by using newline at end of printf string Ex: printf("n= ");

Your code worked in some environments probably because buffering is disabled there.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...