C scanf() function : C Reference



Scanf : Reading or Accepting String From User in C

In C Programming we can use scanf function from stdio.h header file to read string. Scanf function is commonly used for accepting string.

Syntax for Accepting String :

scanf("%s",Name_Of_String_Variable);

Live Example :

#include<stdio.h>

void main()
{
char name[20];
printf("\nEnter the Name : ");
scanf("%s",name);
}

Explanation : Scanf Program

In the above program we are accepting string from user using scnaf() function. We cannot use string ampersand address operator in the scanf() because string itself can be referred by address.

Some Rules and Facts :

  1. Format Specifier %s is used for Accepting String
  2. Scanf() function accepts only String before Space
#include<stdio.h>

int main()
{
char name[20];

printf("\nEnter the Name : ");
scanf("%s",name);

printf("Name of the Company : %s",name);

return(0);
}

Output :

Enter the Name : Google Incl
Name of the Company : Google

We can use scanf to Accept String With Spaces. Just Replace above scanf statement with this following statement –

scanf("%[\^n]", name );

Read more about Reading String with spaces using scanf.

Why We does not need Ampersand Operator :

  1. Scanf() needs a pointer to the variable that will store input.
  2. In the case of a string, you need a pointer to an array of characters in memory big enough to store whatever string is read in.
  3. When you declare something like char var[100], you make space for 100 chars with name[0] referring to the first char and name[99] referring to the 100th char.
  4. The array name by itself evaluates to exactly the same thing as &name[0], which is a pointer to the first character of the sequence, exactly what is needed by scanf.
  5. So all you need to do is  –
  6. scanf("%s", name);