1

I'm writing a program in C for an assignment and I'd like to work on it on my Windows 10 desktop, however I'm encountering a strange issue when using MinGW.

The program I have written is as seen below:

#include <stdio.h>
int main(){
    //set up variables
    int a, b, c, d;

    //prompt user for integers
    printf("Please enter four different integers:\n");
    scanf("%d", &a);
    scanf("%d", &b);
    scanf("%d", &c);
    scanf("%d", &d);

    //return sum
    int sum = a+b+c+d;
    printf("Sum is: %d", sum);

    return 0;
}

When I compile this, the output looks like this: (Where 1, 2, 3 and 4 are the inputted numbers)

1
2
3
4
Please enter four different integers: 
Sum is: 10

This obviously should not happen because that's out of order. To try and troubleshoot, I compiled this same code using GCC on my laptop running Arch and the output looked like this: (Where 1, 2, 3 and 4 are the inputted numbers)

Please enter four different integers:
1
2
3
4 
Sum is: 10

This is what the output should look like. I am using Eclipse Mars as an IDE on both the Linux and the Windows computers. I also tried the same on my other laptop that dual boots Windows 10 and Ubuntu and had the same results between MinGW and GCC.

If anyone has any ideas why MinGW would be acting this way I'd greatly appreciate it! Thanks!

AgentOrange96
  • 79
  • 1
  • 8
  • 1
    possible duplicate of [Flushing buffers in C](http://stackoverflow.com/questions/12450066/flushing-buffers-in-c) – Michael Aaron Safyan Sep 05 '15 at 23:15
  • 1
    You need to flush the buffer using fflush(stdout). See: http://stackoverflow.com/questions/12450066/flushing-buffers-in-c – Michael Aaron Safyan Sep 05 '15 at 23:16
  • i believe that that is about the particular command line used by your IDE, may be cause of input/output event are slightly different on time that are processed (i.e by the command line of the IDE) – Jordy Baylac Sep 05 '15 at 23:21

1 Answers1

2

Different systems/libraries have different heuristics for when to flush the output of a buffered stream. In order to portably ensure that your printf() statement is flushed and printed to the console before reading with scanf(), you need to interleave an explicit call to fflush(stdout).

Michael Aaron Safyan
  • 93,612
  • 16
  • 138
  • 200
  • Thank you! This seems to have been the issue, and I will keep this in mind! I'm new to C (I learned on Java) so I'm still learning. – AgentOrange96 Sep 05 '15 at 23:37