2

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.

Sammy
  • 67
  • 1
  • 5
  • I tried searching in the stackflow but couldn't find one that time. So added the question. Anyway thank you folks... – Sammy Nov 16 '14 at 09:31

2 Answers2

5

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 any FILE * stream, not only stdin.

3

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.

Spikatrix
  • 20,225
  • 7
  • 37
  • 83