【问题标题】:C Console Output not Continuous, Waits until Program FinishesC控制台输出不连续,等到程序完成
【发布时间】:2013-01-04 00:36:55
【问题描述】:

我使用“GCC C 编译器”作为我的编译器,我有一个程序使用“fgets”将输入作为标准输入,然后由于某些输入,我使用多个 printf 来打印结果。

但是,我的问题是我希望输出发生在 fget 之间,它们确实驻留在我的代码中,但是目前在我从 main 返回并且程序结束之前什么都不会打印。

输入代码:

int get_inputs(char** operands, char* delim) {
  if (fgets(input,sizeof(input),stdin) == NULL) return 0;  /* End of file */

  /* Parse with StringParse, returns number of substrings */
  return StringParse(input, operands, delim, 2, "+-*/^ ");
}

输出代码:(在 While(1) 循环中)

count = get_inputs(operands, delim);

switch(count) {
case 0:
    printf("User Terminated\n");
    return 0;  /* User Terminated */

case 1: /* Single Value Input */
    accumulator = atof(operands[0]);
    printf("%g\n", accumulator);
    break;

case 2:
    if(strlen(operands[0]) == 0) { /* Operation First use Accumulator as input */
        accumulator = doMath(accumulator, atof(operands[1]), delim[0]);
        printf("%g\n", accumulator);
    }
    else { /* Two new values, replace Accumulator */
        accumulator = doMath(atof(operands[0]), atof(operands[1]), delim[0]);
        printf("%g\n", accumulator);
    }
    break;

default:
    printf("Invalid Input\n"); /* Invalid Input or Error */
    break;
}

其他所有函数都只是进行数学或字符串解析。

提前致谢!

【问题讨论】:

    标签: c windows eclipse console output


    【解决方案1】:

    这是因为标准输出被缓冲以提高性能。数据仅以较大的块推送到输出管道。要强制这种情况在某个时间点发生,请添加

    fflush(stdout);
    

    在写入标准输出的代码中。

    【讨论】:

      猜你喜欢
      • 2018-08-02
      • 1970-01-01
      • 2021-03-18
      • 2021-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多