【问题标题】:Ambiguous behaviour of printf() with EclipseEclipse 中 printf() 的模棱两可的行为
【发布时间】:2014-05-17 15:53:54
【问题描述】:

我是缓冲流的新手。我正在编写一个简单的c程序,它将一个字符串作为用户输入并显示回来。我的工作环境是windows下的eclipse。代码如下:

#include<stdio.h>

enum { max_string = 127 };

static char string[max_string+1] = ""; 

void main(){
    printf("type the input string---> \n");
    fgets(string,max_string,stdin);
    printf("the input string was ---> %s\n",string);
    }

在运行时,首先获取用户输入,然后执行两个printf()'s。 输出样本为:

user input
type the input string---> 
the input string was ---> user input

我在CodeBlocks IDE中尝试了上面的代码,它运行良好。输出如下:

type the input string--->
user input
the input string was ---> user input

有什么问题? 我还在printf() 的最后添加了一个\n,以便立即刷新它们。

问候。

【问题讨论】:

  • 这似乎是一个 Eclipse/Windows 问题。第一个输出块绝对不是您对行为良好的运行时环境所期望的。
  • @RSahu,那我应该怎么做才能让它工作。
  • printf之后尝试fflush(stdout);
  • @Prakash,谢谢。我想知道,是否有任何永久解决方案可以做到这一点。我的意思是,有什么办法可以禁用这个 extra 缓冲。
  • 使用哪个版本的 Eclipse 您正在观察这种行为。还有它在哪个操作系统上运行。我无法在 Debian Stable 上的 Eclipse Juno SR1 上重现它。

标签: c eclipse stream


【解决方案1】:

stdout 仅在连接到终端时才进行行缓冲。 Eclipse 的终端仿真可能不会被检测为终端。

来自man stdout

流标准输出在指向终端时是行缓冲的。

有几种方法可以绕过这个限制:

  • 每次出现输出时调用fflush(stdout)
  • 像这样使用setvbuf()stdout 设置为无缓冲

    setvbuf(stdout, NULL, _IONBF, 0);
    

    在使用stdout之前。

  • 使用默认不缓冲的stderr

【讨论】:

    【解决方案2】:

    好的!!经过一番谷歌搜索后,我发现 eclipse 终端仿真器比普通终端做更多的缓冲。我们需要在 printf 之后执行 fflush(stdout); 才能使其正常工作。

    【讨论】:

      猜你喜欢
      • 2020-08-25
      • 1970-01-01
      • 2020-06-03
      • 1970-01-01
      • 1970-01-01
      • 2012-06-09
      • 2011-01-09
      • 2017-12-14
      • 1970-01-01
      相关资源
      最近更新 更多