如何在Git bash中运行C程序?

6
我正在使用Windows系统,并使用git bash运行c程序。
我使用gcc编译代码。当我简单地执行printf("hello, world");时,它可以正常工作,但当我尝试创建一个简单的程序来将两个数字相加时,它就不起作用了。
我使用gcc -o sum sum.c进行编译,但是当我使用./sum运行它时,它没有任何反应,但是在命令提示符中运行时,它可以正常运行。
#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);
}

我在 Git Bash 中输入值后得到了这个输出,与 cmd 相比如下:


那么它在Windows命令提示符中产生了预期的输出,但在Git Bash中没有输出?这可能与刷新有关。 - underscore_d
我想支持这个问题,Git bash 首先接受两个输入 ab,然后打印所有的 printf() 语句,但在命令提示符和 PowerShell 中一切都正常工作。 - Rohan Bari
我添加了如何在cmd和git bash中运行sum.c的截图。 - Unknows player
1个回答

5
我通过在这些printf()语句后添加fflush(stdout)解决了这个问题。
printf("Enter first value: ");
fflush(stdout); // this
scanf("%d", &a);

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

在输出内容后,刷新缓冲区会让程序等待您的输入。

工作示例截图:

Git Bash Working Program Example


对我也起作用,但你能解释一下吗?fflush(stdout)在这里实际上是做什么的?为什么在cmd中通常不需要使用fflush(stdout)就可以正常工作? - Unknows player
1
这篇关于C语言自动stdout缓冲刷新规则的帖子可能对你有所帮助。 - Rohan Bari
@RohanBari 还是很奇怪,同一个二进制文件在不同的 shell 中运行时会有不同的行为。 - Jabberwocky
@Jabberwocky没错。这就是为什么我点赞了这个问题并且看到结果感到非常惊讶的原因。 - Rohan Bari

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接