Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between gets and scanf?

Tags:

c

input

gets

scanf

If the code is

scanf("%s\n",message)  

vs

gets(message)

what's the difference?It seems that both of them get input to message.

like image 928
Shihe Zhang Avatar asked Oct 28 '14 07:10

Shihe Zhang


People also ask

What is use of gets () in C?

gets() function in C gets() is a pre-defined function in C which is used to read a string or a text line. And store the input in a well-defined string variable. The function terminates its reading session as soon as it encounters a newline character. Compare the output with the one while using scanf() .

What is the difference gets () and puts ()?

First of all, “gets” is a C library function that reads a line from stdin (standard input) and stores it in the pointed string. In contrast, “puts” is a C library function that writes a string to stdout or standard output. Thus, this is the basic difference between gets and puts in C Language.

Can we use gets after scanf?

We can add a getchar() after scanf() to read an extra newline.

What is the difference between scanf and getchar?

Definition. scanf is a C function to read input from the standard input until encountering whitespace, newline or EOF while getchar is a C function to read a character only from the standard input stream(stdin), which is the keyboard. Thus, this is the main difference between scanf and getchar.


1 Answers

The basic difference [in reference to your particular scenario],

  • scanf() ends taking input upon encountering a whitespace, newline or EOF

  • gets() considers a whitespace as a part of the input string and ends the input upon encountering newline or EOF.

However, to avoid buffer overflow errors and to avoid security risks, its safer to use fgets().

like image 131
Sourav Ghosh Avatar answered Oct 14 '22 14:10

Sourav Ghosh