Issue in C language using 'fgets' after 'printf' as 'fgets' runs before 'printf'

Tanveer Singh picture Tanveer Singh · Jul 20, 2012 · Viewed 7.9k times · Source

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

Answer

AndersK picture AndersK · Jul 20, 2012

do a flush of the stdout

fflush(stdout);

before fgets(...)

printf("Type a String: ");  
fflush(stdout);
fgets(string, max_string, stdin);