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;
}
do a flush of the stdout
fflush(stdout);
before fgets(...)
printf("Type a String: ");
fflush(stdout);
fgets(string, max_string, stdin);
put a \n
in printf
statement. This might be the problem as in C
buffers are line terminated.
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;
}
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, ...
.
来源:https://stackoverflow.com/questions/11575102/issue-in-c-language-using-fgets-after-printf-as-fgets-runs-before-printf