0

I'm using Eclipse IDE I have the following simple code in C language:

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

int main(void) {
    int a;
    printf("Enter a number");
    scanf("%d",&a);
    printf("You have entered %d",a);
    return EXIT_SUCCESS;
}

So as you can see, there are two printf's. but if i run the code on console My scanf is running before my first printf displays. And all output printed together after the execution of scanf.

Then the result will be like this (This is what I'm getting in my console):

6
Enter a numberYou have entered 6

What i really wanted is:

Enter a number
6
You have entered 6

I tried adding fflush(stdout) but the broblem still exists. is there any working solution to fix this?

  • 2
    `fflush(stdout);` between the `printf` and `scanf` lines should work. – Retired Ninja Aug 25 '22 at 12:54
  • Where did you add the `fflush` call? And have you tried running from a command prompt or shell? Does it work as expected then? With or without the `fflush` call? – Some programmer dude Aug 25 '22 at 12:55
  • Either `fflush(stdout);` between the `printf()` and `scanf()` calls or end the printed string with a newline: `printf("Enter a number\n");` – pmg Aug 25 '22 at 12:55
  • @pmg Unfortunately it seems that many IDE's uses pipes to get the program output into its windows. Then `stdout` is fully buffered and not line buffered, so a carefully placed `fflush` is needed. – Some programmer dude Aug 26 '22 at 06:13

0 Answers0