How to run C programs in Git bash?

Viewed 9458

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

1 Answers

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

Related