6

I'm using win 8.1 64bit Eclipse Luna 4.4.0 and compiling with gcc 4.6.4 and the problem is e.g.

in this simple program, my printf and scanf statements are appearing on the console in the wrong order.

#include <stdio.h>
#include <stdlib.h>

int main(void) {

    int i;

    printf("Enter int: ");
    scanf("%d",&i);
    printf("Hello %d\n",i);

    return EXIT_SUCCESS;
}

it does this:

4

Enter int: Hello 4

instead of this:

Enter int: 4

Hello 4

Community
  • 1
  • 1
  • 2
    It's strange a little for me. Try `fflush(stdout);` after the first print –  Oct 17 '14 at 06:35
  • 2
    possible duplicate of [Why does printf not flush after the call unless a newline is in the format string?](http://stackoverflow.com/questions/1716296/why-does-printf-not-flush-after-the-call-unless-a-newline-is-in-the-format-strin) –  Oct 17 '14 at 06:40

1 Answers1

5

printf is buffered1. That means when you call it, it will not immediately print. Instead, it will store what you told it to print, and automatically print it when enough text has been stored in the buffer.

If you use a \n after in your print statement, it will automatically print the whole buffer (that's why the last call to printf prints everything). For your case, you may want to use a manual flush with fflush

printf("Enter int: "); fflush(stdout);
scanf("%d",&i);
printf("Hello %d\n",i);

1 Technically, it's stdout which is buffered, but it's easier to think of it as printf being buffered at this point.

just.another.programmer
  • 8,579
  • 8
  • 51
  • 90