6

I'm on Windows and I'm using git bash to run my c program.

I use gcc to compile the code. When I just do a simple printf("hello, world"); it works, but when I try to create a simple program that adds two numbers it just does nothing.

It compiles with gcc -o sum sum.c but when I run it using ./sum it does nothing, but when I run it in my command prompt it runs normally.

#include <stdio.h>

int main(void) {
    int n1, n2;

    printf("Enter a number: ");
    scanf("%d", &n1);
    printf("Enter another number: ");
    scanf("%d", &n2);

    int sum = n1 + n2;

    printf("Sum: %d\n", sum);
}

I tried Entering values in the git bash and got this output compared to cmd

mike
  • 1,233
  • 1
  • 15
  • 36
Unknows player
  • 97
  • 1
  • 1
  • 5
  • So it produces the expected output in the Windows Command Prompt but none in Git Bash? It might be to do with flushing then. – underscore_d May 27 '20 at 10:42
  • I'd like to support this question, Git bash accepts two inputs `a` and `b` first and then prints all the `printf()` statements but everything's working fine in Command Prompt and PowerShell. – Rohan Bari May 27 '20 at 10:43
  • I added screenshots of how I ran sum.c in both cmd and git bash – Unknows player May 27 '20 at 10:55

1 Answers1

5

I got this problem fixed by appending fflush(stdout) after those printf() statements:

printf("Enter first value: ");
fflush(stdout); // this
scanf("%d", &a);

printf("Enter second value: ");
fflush(stdout); // this
scanf("%d", &b);

Just flushing the buffer will let the program wait for your input after printing.

The working example screenshot:

Git Bash Working Program Example

Rohan Bari
  • 7,482
  • 3
  • 14
  • 34
  • It works to me too but can you explain. What does `fflush(stdout)` actually do here. And why does it work normally in cmd without the use of `fflush(stdout)` – Unknows player May 27 '20 at 11:18
  • 1
    [What are the rules of automatic stdout buffer flushing in C](https://stackoverflow.com/a/39536803/11471113) thread might be helpful for you in this case. – Rohan Bari May 27 '20 at 11:21
  • @RohanBari it's still strange that the same binary has different behaviour depending on the shell it is run from. – Jabberwocky May 27 '20 at 11:59