5

Possible Duplicate:
Why does printf not flush after the call unless a newline is in the format string? (in C)

I am getting a problem using printf and fgets as in my code printf is written earlier then fget but it does not run, it runs after fgets runs.

enum { max_string = 127 };
static char string[max_string+1] = "";

int main( int argc, char ** argv ) {    
      printf("Type a String: ");
      fgets(string, max_string, stdin);
      printf("The String is %s\n", string);
      return 0;
}
Community
  • 1
  • 1
Tanveer Singh
  • 51
  • 1
  • 5

4 Answers4

7

do a flush of the stdout

fflush(stdout);

before fgets(...)

printf("Type a String: ");  
fflush(stdout);
fgets(string, max_string, stdin); 
AndersK
  • 33,910
  • 6
  • 56
  • 81
1

The point is not that printf runs after fgets, but instead that its output is displayed after it.

This happens because standard output (the file descriptor you're writing on with printf) is line-buffered, i.e. the standard library defers prints after a newline character (\n) has been received for printing.

From man stdout:

The stream stdout is line-buffered when it points to a terminal. Partial lines will not appear until fflush(3) or exit(3) is called, or a newline is printed.

To investigate different results, edit your example to use fflush, or print on standard error using fprintf(stderr, ... .

Marco Leogrande
  • 6,894
  • 2
  • 27
  • 47
0

put a \n in printf statement. This might be the problem as in C buffers are line terminated.

Kiril Kirov
  • 35,473
  • 22
  • 102
  • 177
neel
  • 6,447
  • 4
  • 29
  • 48
0

Neel is right. If you want to just write something down without having to put that '\n' you can use the function write();

#include <stdio.h>
#include <unistd.h>
#include <string.h>

enum { max_string = 127 };
static char string[max_string+1] = "";


my_putstr(char *str)
{
     write(1, str, strlen(str));
}

int main( int argc, char ** argv ) {    
    my_putstr("Type a String: ");  
    fgets(string, max_string, stdin); 
    printf("The String is %s\n", string);
    return 0;
}
cp151
  • 178
  • 2
  • 17