I've recently started learning C programming language and saw these three input function in 3 different books. So I'm little confused about which one to use when efficiency is considered.
2 Answers
So I'm little confused about which one to use when efficiency is considered.
None of them. I/O is slow. If you need efficiency, don't do I/O. Or, what's more likely is that you don't really need efficiency but you need I/O and you are optimizing prematurely.
Apart from that, here's the difference:
gets()
is dangerous and has been removed from the standard, don't use it.scanf()
is standard, but it's clumsy and hard to use correctly. Apart from very specialized use cases, it's not worth bothering with it.fgets()
is easier to use correctly and it is the preferred way of getting raw untrusted user input (i. e. user input in general). It can also read from anyFILE *
stream, not onlystdin
.

- 9,223
- 3
- 25
- 38
gets()
reads always from standard input (stdin
)
fgets()
can read from an input stream (e.g. a file you open explicitly)
So, gets()
is equal to fgets()
with third parameter as stdin
.
At last, scanf()
can read formatted input data, parse it and set values to pointers you give.
Never use gets()
. It offers no protections against a buffer overflow vulnerability.
Avoid using scanf()
. If not used carefully, it can have the same buffer overflow problems as gets()
.
You should use fgets()
instead, although it's sometimes inconvenient.

- 20,225
- 7
- 37
- 83

- 1,341
- 2
- 15
- 33
-
1"gets() is equal to fgets() with third parameter as stdin" Hmmmm - A difference is with `gets()`: newline character, if found, is not copied. newline character, if found, is copied with `fgets()`. – chux - Reinstate Monica Nov 16 '14 at 20:44
-
Yes, you can remove it explicitly "string[strlen(string) - 1] = '\0'; – Efstathios Chatzikyriakidis Nov 16 '14 at 23:12
-
`string[strlen(string) - 1] = '\0` is a problem as it leads to trouble in the exceptional cases when `strlen(string) == 0`. Methods exist to [quickly](http://codereview.stackexchange.com/questions/67608/trimming-fgets-strlen-or-strtok) and safely remove the `'\n'` – chux - Reinstate Monica Nov 17 '14 at 00:19
-
Of course you have to check the length of the string and if the last character is the newline character. That was to easy to add it here. – Efstathios Chatzikyriakidis Nov 17 '14 at 07:59