Try it here
scanf() and gets() in C

When and Where to use scanf() and gets() in C



scanf() allows us to enter data from keyboard that will be formatted in a certain way.

The genaral form of scanf() statement is as follows :

scanf("format string",list of addresses of variables);

For example:

scanf("%d %f %c",&c &a &ch);

Note that we are sending addresses of variables (addresses are obtained by using '&' the 'address of' operator) to scanf() function. This is necessary because the values received from keyboard must be dropped into variables corresponding to these addresses. The values that are supplied through the keyboard must be separated by either blank(s), tab(s), or newline(s). Do not include these escape sequences in the format string.


gets() receives a string from the keyboard. scanf() has some limitations while a receiving a string of characters.There is no way to enter a multi-word string into a single variable. gets() function gets a string from the keyboard and it is terminated when an Enter Key is hit.Thus, spaces and tabs are perfectly acceptable as part of the input string. gets() gets a newline ( ) terminated string of characters from the keyboard and replaces the with a .

    char player[40];

    puts("Enter name");
    gets(player); /*sends base address of array */
    puts("Happy plying !");

Following is the sample output:

Enter name
Kapil Dev
Happy Playing !
Kapil Dev

Difference between scanf()and gets()

The main difference between scanf() and gets() is:

  1. scanf() reads input until it encounters whitespace, newline or End Of File(EOF) whereas gets() reads input until it encounters newline or End Of File(EOF), gets() does not stop reading input when it encounters whitespace instead it takes whitespace as a string.
  2. scanf()can read multiple values of different data types whereas gets() will only get character string data. gets() can be used to read one string at a time.

Writer profile pic

Uk01 on Feb 06, 2015 at 12:02 am

If you like and would like to contribute, you can write your article here or mail your article to . See your article appearing on the main page and help others to learn.

Post Comment

Comments( 0)


Forgot Password

Please enter your email address below and we will send you information to change your password.