Question

I am a newbie to buffered streams.I was write a simple c program which takes a string as a user input and displays it back.My working environment is eclipse under windows.The code is as follow:

#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);
    }

While running it,the user input is taken first and the two printf()'s are executed after. The output sample is:

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

I tried the upper code in CodeBlocks IDE and it worked fine.The output is as follow:

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

What is the problem? I also added a \n at the last of my printf() so as to flush them immediately.

Regards.

Was it helpful?

Solution

stdout is line-buffered only if connected to a terminal. Eclipse's terminal-emulation might not be detected as terminal.

From man stdout:

The stream stdout is line-buffered when it points to a terminal.

There are several way to get around this limitation:

  • call fflush(stdout) every time output shall appear
  • set stdout to be unbuffered by using setvbuf() like this

    setvbuf(stdout, NULL, _IONBF, 0);
    

    prior to using stdout.

  • use stderr which isn't buffered by default

OTHER TIPS

OK!! after some googling i found out that the eclipse terminal emulator do more buffering than the normal terminal.We need to do fflush(stdout); after the printf to make it working.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top