1
#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 ?

PEHLAJ
  • 9,980
  • 9
  • 41
  • 53
thiennt
  • 51
  • 1
  • 2
  • 8

1 Answers1

6

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 \n at end of printf string Ex: printf("n= \n");

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

Aravind Voggu
  • 1,491
  • 12
  • 17
  • this code: printf("n= \n"); doesn't work for me. And when we flush stdout buffer. data transfer to stdout ? – thiennt May 21 '17 at 17:58
  • @NguyễnTiếnThiên You mean to say `printf("n= \n");` doesn't print or it makes your input go to a new line and you don't like it? – Aravind Voggu May 21 '17 at 18:10
  • @JonathanLeffler Thanks for that. I thought some compilers allowed `scanf` to print to `stdout`. but as I see, `scanf` is not meant to do that. So I removed that suggestion. Yeah, that `%s` is a typo. Thanks :) – Aravind Voggu May 22 '17 at 03:32