What is difference between gets() and scanf() function?

Answer : scanf() uses printf()’s format strings. Thus you have to tell it for example that you want a string, a float, an integer character of some kind or a char. In fact, the first difference is you can enter any of the basic types that way and the second difference is that you use the format string to tell it what you enter. Gets() enters strings period.

Scanf() does format your input. If you enter a whitespace character like a space or — anything else — your string ends whether you want it to or not. Gets() does not. You type until you reach a newline character (hit enter). When it encounters that, that is your string.

One similarity is kinda dangerous, and leads to the next difference I can think of. Neither checks, when using strings, that the strings are valid pointers to arrays of sufficient length to hold the characters you are sending to them. C tends to treat arrays and pointers the same way, so this behavior can cause crashes or worse if you send your data to or try to read it from uninitialized pointers.

Gcc likes scanf(). If you compile a program with gets you get the following in GCC:
/tmp/ccmTbwvW.o: In function `main’:
get.c:(.text+0x24): warning: the `gets’ function is dangerous and should not be used.
You don’t get that “problem” with scanf.

Finally you can do a:
HelloString=gets(Hellostring);

Gets() returns another pointer to your array of char which you can throw away if you like. Scanf() also has a return. It returns the number of items successfully read or EOF.

Leave a comment