-
fgets help?
I new to C and I'm learning how to get input for strings.I showed this on a other forum and they said I did it wrong I corrected it but they really didn't explain what was wrong with it.
here is my code
Code:
#include<stdio.h>
int main()
{
char userinput[256];
printf("Enter a string:");
fgets(userinput,sizeof userinput,stdin);
printf("%s",userinput);
return 0;
}
And here is the corrected one can someone please explain why I flush stdout and put a if there
Code:
#include<stdio.h>
int main ( void )
{
char userinput[256];
printf ( "Enter a string: " );
fflush ( stdout );
if ( fgets ( userinput, sizeof userinput, stdin ) != NULL )
printf ( "%s", userinput );
return 0;
}
-
The flush is done because stdout is line buffered by default, and there is no guarentee that the prompt message will be sent to the user before you try to read a line because you didn't append a '\n' to what was printed.
The if statement is guarenteeing that fgets() worked. If it returned NULL, then something wrong happened. You should not treat the buffer as if it has a string from the user until you find out what happened.
-
To be on a saver side and for the neatness thye fflush(stdout) is been used. But the return values of fgets should be checked ways.
ssharish2005