Question

#include <stdio.h>

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

int main( int argc, char ** argv ) {
    printf("Type a string");
    fgets(string, max_size_string, stdin);
    printf("The string is %s",string);
    return 0;
}

In console screen, Type a string is appearing after typing something, and after that, other printf is printing the output. I am unable to understand the order of execution.

enter image description here

Was it helpful?

Solution

I think the problem is that printf() buffers output until either

  • it gets a line ending (\n)
  • you fflush(stdout)
  • you close the stream (including it closing automatically when the program exits)

See if the following makes more sense

printf("Type a string ");
fflush(stdout);
fgets(string, max_size_string, stdin);
printf("The string is %s\n",string); // << Note I've added a line ending
return 0;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top