If the code is
scanf("%s\n",message)
vs
gets(message)
what's the difference?It seems that both of them get input to message.
If the code is
scanf("%s\n",message)
vs
gets(message)
what's the difference?It seems that both of them get input to message.
The main difference is that
gets
reads until EOF or\n
, whilescanf("%s")
reads until any whitespace has been encountered.scanf
also provides more formatting options, but at the same time it has worse type safety thangets
.Another big difference is that
scanf
is a standard C function, whilegets
has been removed from the language, since it was both superfluous and dangerous: there was no protection against buffer overruns. The very same security flaw exists with scanf however, so neither of those two functions should be used in production code.You should always use
fgets
, the C standard itself even recommends this, see C11 K.3.5.4.1(emphasis mine)
scanf()
is much more flexible tool whilegets()
only gets one variable at a time.gets() is unsafe, for example: char str[1]; gets(str) if you input more then the length, it will end with SIGSEGV. if only can use gets, use malloc as the base variable.
There are several. One is that gets() will only get character string data. Another is that gets() will get only one variable at a time. scanf() on the other hand is a much, much more flexible tool. It can read multiple items of different data types.
In the particular example you have picked, there is not much of a difference.
The basic difference [in reference to your particular scenario],
scanf()
ends taking input upon encountering awhitespace
,newline
orEOF
gets()
considers a whitespace as a part of the input string and ends the input upon encounteringnewline
orEOF
.However, to avoid buffer overflow errors and to avoid security risks, its safer to use
fgets()
.Disambiguation: In the following context I'd consider "safe" if not leading to trouble when correctly used. And "unsafe" if the "unsafetyness" cannot be maneuvered around.
In terms of safety there is no difference, both read in from
Standard Input
and might very well overflowmessage
, if the user enters more data thenmessage
provides memory for.Whereas
scanf()
allows you to be used safely by specifying the maximum amount of data to be scanned in:With
gets()
it is not possible to specify the maximum number of characters be read in, that's why the latter shall not be used!