A C problem using "fgets" after "printf" as "fgets" runs before "printf"

Possible duplicate:
Why printf is not cleared after a call if a new line is not specified in the format string? (in C)

I have a problem with printf and fgets , since in my code printf is written earlier and then fget, but it does not start, it starts after fgets .

 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; } 
+4
source share
4 answers

reset stdout

 fflush(stdout); 

before fgets(...)

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

type the \n operator in printf . This can be a problem, since line C is complete in buffer C

0
source

Neal is right. If you want to just write something without adding this "\ n", you can use the write () function;

 #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; } 
0
source

It's not that printf works after fgets , but instead, its output is printed after it.

This is due to the fact that the standard output (the file descriptor that you write with printf ) is line-buffered, that is, the standard library discards prints after the newline character ( \n ) for printing. A.

From man stdout :

The stdout of the stream is buffered by line when it points to the terminal. Partial lines will not be displayed until fflush (3) or exit (3) is called, or a new line is printed.

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

0
source

All Articles