0

I was reading this question on quora and read that google asked this question in one of its interviews,

What are the differences between the functions : scanf("%s"),gets and getline

Can anyone provide an exhaustive list and their explanation.

Gaurav Arora
  • 183
  • 2
  • 10

1 Answers1

7

scanf("%s", &buffer); read next token (any space/end of line/tabulation will end the token) in input and store it in the char *buffer. You should use a format with a maximum size to buffer, for instance with char buffer[10] you should use scanf("%9s", buffer); to read at most 9 characters.

gets() is obsolete, do not use it. It read a full line, whatever it's size, so if a program with admin privilege uses such a crappy function it can be used by hackers to penetrate the system. This used to be a common hacker's tactic. Please use fgets() instead, it takes a parameter with the size of your buffer. fgets(buffer, 10, stdin); with my previous example. Please note the \n will be included in the buffer if the line is not more than 8 characters.

getline() is more specific, for what I know it's a c++ function only.

Spikatrix
  • 20,225
  • 7
  • 37
  • 83
jdarthenay
  • 3,062
  • 1
  • 15
  • 20
  • 4
    [`getline` is available in C](http://man7.org/linux/man-pages/man3/getline.3.html), although it is not standard C. It is a POSIX.1-2008 function – Spikatrix Apr 08 '16 at 06:34