I want to know what is the difference between fgets() and scanf(). I am using C as my platform.
Scanf does not perform bounds checking. fgets is likely going to be the better choice. You can then use sscanf() to evaluate it.
Good discussion of the topic here- http://cboard.cprogramming.com/c-programming/109243-scanf-vs-fgets.html
http://stackoverflow.com/questions/1247989/how-do-you-allow-spaces-to-be-entered-using-scanf/1247993#1247993 (That was my evil twin getting lectured for forgetting this- not me)
scanf parses a string you read in (or created), and fgets reads a line from an open FILE*. Or do you mean fscanf?
There are multiple differences. Two crucial ones are:
fgets()
can read from any open file, butscanf()
only reads standard input.fgets()
reads 'a line of text' from a file;scanf()
can be used for that but also handles conversions from string to built in numeric types.
Many people will use fgets()
to read a line of data and then use sscanf()
to dissect it.
*int scanf(const char * restrict format, ...);*
scanf(3) searches for certain pattern defined by the format argument on the given input known as stdin, where the pattern is defined by you. The given input to scanf(3), depending on its variant (scanf, fscanf, sscanf, vscanf, vsscanf, vfscanf), could be a string or a file.
*char *fgets(char * restrict str, int size, FILE * restrict stream);*
fgets(3) just reads a line from the input file stream and copy the bytes as null terminating string to the buffer str and limit the ouput to the buffer to given bytes in size.