【问题标题】:How to run C programs in Git bash?如何在 Git bash 中运行 C 程序?
【发布时间】:2020-05-27 10:28:01
【问题描述】:

我在 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 中却没有?这可能与冲洗有关。
  • 我想支持这个问题,Git bash 首先接受两个输入 ab,然后打印所有 printf() 语句,但在命令提示符和 PowerShell 中一切正常。
  • 我添加了我如何在 cmd 和 git bash 中运行 sum.c 的屏幕截图

标签: c git-bash


【解决方案1】:

我通过在那些 printf() 语句之后附加 fflush(stdout) 解决了这个问题:

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

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

只需刷新缓冲区即可让程序在打印后等待您的输入。

工作示例截图:

【讨论】:

  • 它也适用于我,但你能解释一下吗? fflush(stdout) 在这里实际上做了什么。以及为什么不使用fflush(stdout)在cmd中能正常工作@
  • What are the rules of automatic stdout buffer flushing in C 线程在这种情况下可能对您有所帮助。
  • @RohanBari 仍然很奇怪,同一个二进制文件根据运行它的 shell 有不同的行为。
  • @Jabberwocky 是的。这就是我对这个问题投赞成票的原因,看到结果我真的很惊讶。
猜你喜欢
  • 2010-10-13
  • 2020-03-24
  • 2021-07-07
  • 1970-01-01
  • 2021-01-10
  • 1970-01-01
  • 2015-02-22
  • 2021-06-06
  • 2016-07-23
相关资源
最近更新 更多