Gaurav Arora
Gaurav Arora

Reputation: 183

Difference btw gets, scanf('%s'), getline

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.

Upvotes: 0

Views: 7496

Answers (1)

jdarthenay
jdarthenay

Reputation: 3147

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.

Upvotes: 7

Related Questions