Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between scanf() and fgets()

Tags:

c

fgets

scanf

I want to know what is the difference between fgets() and scanf(). I am using C as my platform.

like image 846
Biswajyoti Das Avatar asked Aug 09 '09 20:08

Biswajyoti Das


People also ask

What is the difference between scanf and scanf?

sscanf() reads formatted input from a string. scanf() reads formatted input from stdin . So in your example sscanf reads from the first argument of the program and saves it in the variable port .

What is difference between fgets?

Even though both the functions, gets() and fgets() can be used for reading string inputs. The biggest difference between the two is the fact that the latter allows the user to specify the buffer size. Hence it is highly recommended over the gets() function.

What is the difference between scanf and getchar?

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

There are multiple differences. Two crucial ones are:

  • fgets() can read from any open file, but scanf() only reads standard input.
  • fgets() reads 'a line of text' from a file; scanf() can be used for that but also handles conversions from string to built in numeric types.

Many people will use fgets() to read a line of data and then use sscanf() to dissect it.

like image 80
Jonathan Leffler Avatar answered Oct 08 '22 11:10

Jonathan Leffler