Input Using Scanf Function in C

The scanf is the standard input formatting function in the C language. It is used to read all types of general data such as integers, floating-point numbers and characters, and strings. This function takes a text stream from the keyboard, extracts and formats data from the stream according to a format control string, and stores the data in specified program variables. For example, the stream of seven characters ‘1’, ‘2’, ‘3’, ‘4’, ‘.’, ‘5’, and ‘6’ are extracted as 1234.56

All the conversion specifiers or format specifiers we were used with printf C, also can be used with scanf function.

Table Of Contents

modifiers in scanf c

Conversion Specifiers for scanf in C

The following table represents some of the conversion codes:

Conversion code Usual variable type Display
%c char Read a single character
%d or %i int Read a singed decimal integer
%u int Read unsigned decimal integer
%o int Read unsigned octal value
%x or %X int Read unsigned hex value
%f float or
double
Read signed floating point
%e or %E float or
double
Read signed exponential format
%g or %G float or
double
Use %f or %e, whichever is shorter
%s array of
char
Read sequence of characters (string)
%p pointer Read in hex address stored in pointer
%% none No corresponding argument is converted
%n pointer of int No characters in the input stream are matched.
The corresponding argument is a pointer to an
integer into which the number of characters read is placed.

An optional conversion-code modifier, which modifies the conversion code to accept format for a type of:
h = short int
l = long int
ll = long long int
L = long double

For more learn:- size modifier in printf function

Reading values using scanf function in C language

Reading only one Integer value using scanf function

 #include<stdio.h>
 int main()
 {
   int num;
   printf("Enter a number: ");
   scanf("%d",&num);
   printf("Entered number = %d", num);
   return 0;
 }

Output:-

Enter a number: 50
Entered number = 50

Reading more than one Integer value using scanf function

 #include<stdio.h>
 int main()
 {
   int num1, num2;
   printf("Enter two number: ");
   scanf("%d %d",&num1, &num2);
   printf("Entered numbers are = %d and %d", num1, num2);
   return 0;
 }

Output:-

Enter two number: 10 20
Entered numbers are = 10 and 20

Reading multiple data type values by using scanf function

 #include<stdio.h>
 int main()
 {
   int mark;
   float height;
   char grade;
   printf("Enter mark, height, and grade: ");
   scanf("%d %f %c",&mark, &height, &grade);
   printf("Entered values are:\n");
   printf("Mark = %d\n", mark);
   printf("Height = %.2f\n", height);
   printf("Grade = %c", grade);
   return 0;
 }

Output:-

Enter mark, height, and grade: 90 4.2 A
Entered values are:
Mark = 90
Height = 4.20
Grade = A

Importance of ampersand (&) in scanf function in C

To store values in memory locations associated with variables, the scanf() function should have the addresses of the variables rather than just their values. This means that simple variables have to be passed with a preceding ‘&’.

Program without using & in printf() functions will throw a warning and you will get unexpected results.

 #include<stdio.h>
 int main()
 {
   int num=0;
   printf("Enter a number: ");
   scanf("%d",num);
   printf("Entered number = %d", num);
   return 0;
 }

Output:-

Enter a number: 5
Segmentation fault (core dumped)

Note:- There is no need to use ‘&’ for arrays and strings because they are an explicit pointer. In arrays and strings ‘&’ is optional. Why & is optional, you will understand after learning pointer concepts.

 #include<stdio.h>
 int main()
 {
   char ch[10]; //string
   
   //Reading without using &
   printf("Enter a string: ");
   scanf("%s",ch);
   printf("%s\n",ch);
   
   //Reading with using &
   printf("Enter a string: ");
   scanf("%s",&ch);
   printf("%s\n",ch);
   return 0;
 }

Output:-

Enter a string: Know
Know

Enter a string: Program
Program

Now consider some examples for a better understanding of the ampersand (&) operator in scanf function in C language.

 #include<stdio.h>
 int main()
 {
   int x, y, z;
   x=10, y=20, z=30;
   printf("Enter three numbers: ");
   scanf("%d %d",&x, &y, &z);
   printf("%d %d %d", x, y, z);
   return 0;
 }

Output:-

Enter three numbers: 50 60 70
50 60 30

This program has three addresses but only two conversion specifiers. So, the scanf will read only the first two values and store it in the associated variables, the third entered value will be ignored.

 #include<stdio.h>
 int main()
 {
   int a, b, c;
   a=10, b=20, c=30;
   printf("Enter three numbers: ");
   scanf("%d %d %d",&a, &b);
   printf("%d %d %d", a, b, c);
   return 0;
 }

Output:-

Enter three numbers: 5 15 25
Segmentation fault (core dumped)

You may get unexpected output for the above program.

Width modifier in scanf in C Language

In scanf function, if we specify the width modifier then it specifies the maximum characters to be read. The scanf will read either as many characters are specified by the width modifier or until it sees the white space, whichever happens first.

 #include<stdio.h>
 int main()
 {
   int a;
   printf("Enter a number: ");
   scanf("%3d",&a);
   printf("%d", a);
   return 0;
 }

Output:-

Enter a number: 123456789
123

Enter a number: 1 2 3 4 5
1

The following are the reasons which can stop the scanf function from reading a value for the variable.
1) When a white space is found after a digit in a numeric sequence.
2) The maximum number of characters has been processed.
3) An EOF (end of file) character is reached.
4) An error is detected.

When reading from an actual disk file, there is automatically an end-of-file character at the end of the file. When reading from the keyboard, the user can simulate one by pressing a specific character sequence. On the Windows operating system, we can enter end-of-file by pressing Ctrl+Z. Similarly, for the Linux operating system, we can use Ctrl+D

The other reason scanf() may stop when it encounters an invalid input. For example, in place of the number if we press a non-numeric character then it is an error.

Precision Modifier

The precision modifier can’t be used with scanf function.

 #include<stdio.h>
 int main()
 {
   float a;
   a=10.5;
   scanf("%5.2f",&a);
   printf("%f", a);
   return 0;
 }

Output:-

12.48
10.500000

This example has precision with conversion specification in the scanf. When scanf finds a precision, it stops processing and returns to the function that called it. Hence, the input variable is unchanged.

Returning value from the scanf in C language

The scanf function returns the number of input fields successfully scanned, converted and stored in specified program variables. The return value does not include the values which are scanned but not stored in any variable. If scanf() attempts to read end-of-file, the return value is EOF. If no fields were stored the return value is 0.

 #include<stdio.h>
 int main()
 {
   int x, y, z, num;
   
   printf("Enter three numbers: ");
   num = scanf("%d %d %d",&x,&y,&z);
   printf("%d\n", num);
   
   printf("Enter three numbers: ");
   num = scanf("%d",&x,&y,&z);
   printf("%d\n", num);

   return 0;
 }

Output:-

Enter three numbers: 10 20 30
3

Enter three numbers: 5 15 25
1

When we are reading from the keyboard, then the input is buffered. When the user presses the enter key, then the buffer is sent to the program. Before pressing enter key, the user can edit the buffer by adding new characters, or by hitting the backspace or delete key to remove the last character from the buffer.

Constant text in scanf

The format string/control string in scanf() has the following general form:

"< character string > < %conversion specifier field >"

Here character string is optional and has to be used with care.

Generally, the format string for a scanf() will not contain constant text. If we use constant text in the scanf then the input must contain the same text in the same position.

 #include<stdio.h>
 int main()
 {
   int x, y, z;
   printf("Enter three numbers: ");
   scanf("%d, %d, %d",&x,&y,&z);
   printf("%d %d %d", x,y,z);
   return 0;
 }

Output:-

Enter three numbers: 10,20,30
10 20 30

Enter three numbers: 10 20 30
10 -1670398848 32767

Notice that in this program, inside scanf function we are using a constant character comma (,) so, at the time of input we should use ‘,’ operator. If we don’t use the comma operator then we will get unexpected results.

To avoid this type of problem, it is usually a good idea not to include constant text in format strings when using scanf().

 #include<stdio.h>
 int main()
 {
   int month, day, year;
   printf("Enter today date (in mm-dd-yy format): ");
   scanf("%d-%d-%d",&month,&day,&year);
   printf("Month = %d\n", month);
   printf("Day = %d\n", day);
   printf("Year = %d\n", year);
   return 0;
 }

Output:-

Enter today date (in mm-dd-yy format): 12-31-20
Month = 12
Day = 31
Year = 20

White space in scanf

When scanf function reads any number then it skips white spaces, tabs and newlines. All these spaces are ignored and the scanf function will keep reading until it reaches a number.

 #include<stdio.h>
 int main()
 {
   int a,b,c;
   printf("Enter three numbers: ");
   scanf("%d %d %d",&a,&b,&c);
   printf("Entered numbers are: ");
   printf("%d %d %d",a,b,c);
   return 0;
 }

Output:-

Enter three numbers: 10 25 50
Entered numbers are: 10 25 50

Enter three numbers:
50
100
250
Entered numbers are: 50 100 250

We are entering input in the same lines or in different lines, it doesn’t matter. The scanf() will ignore all the spaces.

 #include<stdio.h>
 int main()
 {
   int x,y,z;
   char ch;
   printf("Enter three numbers and one character: ");
   scanf("%d%d%d%c",&x,&y,&z,&ch);
   printf("Entered values are: ");
   printf("%d %d %d %c",x,y,z,ch);
   return 0;
 }

Output:-

Enter three numbers and one character: 1 2 3a
Entered values are: 1 2 3 a

Enter three numbers and one character: 10 20 30 a
Entered values are: 10 20 30

Note:- The statement scanf("%d%d%d",&x,&y,&z); and scanf("%d %d %d",&x,&y,&z); both are the same.

Suppression Character in scanf

Suppression character (*) is used to skip the input field in between % sign and the conversion specification. The scanf read the input field but for suppression character, value is not assigned.

 #include<stdio.h>
 int main()
 {
   int a,b,c,d;
   printf("Enter four number: ");
   scanf("%d %*d %d %*d",&a,&b,&c,&d);
   printf("%d %d %d %d",a,b,c,d);
   return 0;
 }

Output:-

Enter four number: 10 20 30 40
10 30 1772494544 32766

In this program, scanf read four integer but only two are stored in the variables a and b, the remaining two numbers are not stored in any variables due to suppression character.

 #include<stdio.h>
 int main()
 {
   int month, day, year;
   printf("Enter today date (in mm-dd-yy or mm/dd/yy format): ");
   scanf("%d %*c %d %*c %d", &month, &day, &year );
   printf("Month = %d\n", month);
   printf("Day = %d\n", day);
   printf("Year = %d\n", year);
   return 0;
 }

Output:-

Enter today date (in mm-dd-yy or mm/dd/yy format): 01-01-21
Month = 1
Day = 1
Year = 21

Enter today date (in mm-dd-yy or mm/dd/yy format): 10/10/22
Month = 10
Day = 10
Year = 22

Some Problem with scanf function

#Case1:- Use ampersand in correct way

 #include<stdio.h>
 int main()
 {
   int a, b;
   a=10, b=20;

   printf("Enter two numbers: ");
   scanf("%d",&a, &b);
   printf("first scanf executed.\n");

   printf("Enter one number: ");
   scanf("%d",&b);
   printf("\nEntered numbers are: ");

   printf("%d %d", a, b);
   return 0;
 }

Output:-

Enter two numbers: 9 18
first scanf executed.
Enter one number:
Entered numbers are: 9 18

In this program, the first scanf has two addresses but only one conversion specifier. So, it will read only one value and store it in the variable a, the second entered value will remain in the stream and waiting to be read. Later, we want to read another number using scanf. This time scanf will not wait for the user to enter the number because there is already a number in the stream waiting to be read. So, the scanf will read the value from stream and store it in the variable b.

 #include<stdio.h>
 int main()
 {
   int a, b;
   a=10, b=20;
   scanf("%d",&a);
   printf("first scanf executed.\n");
   scanf("%d",&b);
   printf("%d %d", a, b);
   return 0;
 }

Output:-

9 18
first scanf executed.
9 18

This program is similar to the previous problem. In this program first scanf has only one conversion specifier and only one address, but we are giving two inputs for this scanf. The first scanf we read-only value, the second value is in the stream waiting to be read. The next scanf function read this value. It will not wait for the user to enter the number.

Solution for this problem

To avoid this problem, use scanf("%[^\n]"); before the second scanf() in the previous program. It will clear the stream.

 #include<stdio.h>
 int main()
 {
   int a, b;
   a=10, b=20;
   printf("Enter two numbers: ");
   scanf("%d",&a, &b);
   printf("The first scanf executed.\n");
   scanf("%[^\n]");
   printf("Enter one number: ");
   scanf("%d",&b);
   printf("\nEntered numbers are: ");
   printf("%d %d", a, b);
   return 0;
 }

Output:-

Enter two numbers: 9 18
The first scanf executed.
Enter one number: 555
Entered numbers are: 9 555

#Case2:- Use scanf() correctly with char

Guess the output of the below program.

Input for the below program:-
x
y
z

 #include<stdio.h>
 int main()
 {
   char a,b,c;

   scanf("%c",&a); //Enter 'x'
   scanf("%c",&b); //Enter 'y'
   scanf("%c",&c); //Enter 'z'

   printf("%c,%c,%c\n",a,b,c);

   return 0;
 }

Expected Output:
x
y
z

But the real output is different from expected output. Why?
Because we are not using scanf() correctly.

The scanf() takes input from the standard input devices (i.e keyboard), and in this case, it takes only one character at a time.

When we give first input as ‘x’ and hit enter, that enter is itself a character (‘\n’) and it is taken as input for the second scanf(). When we enter,’y’ it is actually stored in the last scanf() i.e for variable c. So,

Variable a holds ‘x’
Variable b holds ‘\n’
And the variable c holds ‘y’.
That’s why we got unexpected output.

What is the correct way?
Give a space before %c in the scanf() statement:

scanf("%c",&a);
scanf(" %c",&b);
scanf(" %c",&c); 

This way we are telling scanf() to automatically eat trailing white spaces and special characters, like enter.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

Test your Knowledge:-

Leave a Reply