The scanf() Function

The scanf() function is used to get formatted input from stdin (keyboard). The data that is read from the standard input can be assigned to a variable. The scanf function has the general form

int scanf("format string",[variable_pointers,...]);

Format String

The first argument is a string which is made up of conversion specifiers that specify how to convert the data that is read from the input stream. Commonly used conversion specifiers are

Conversion specifierType
%cSingle Character
%sCharacter String

Variable Pointers

The format string argument is followed by any number of variable pointers, one for each conversion specifier in the format string. The data that is read from the stdin is assigned to these variables. The variable and their corresponding conversion specifier must be of the same type otherwise no value will be assigned to the variable. scanf function will abort if the input data and conversion specifiers do not match.

Return Value

The return value of scanf function is the number of successful data inputs.


#include <stdio.h>
int main ()
int i;
char ch;
scanf ("%d %c",&i,&ch);
return 0;

In this example i is a integer variable and ch is a character variable. &i and &ch are pointers to variables i and ch respectively.

The program expects the user to input a integer value first and then a character. If the user inputs


In this case, scanf will set the variable i=10 and ch=x. If the user inputs


In this case scanf will abort and no value will be assigned to the variables i and ch since the first input was a character and it did not match the conversion specifier.

Post a comment


Your Comment

Email (We dont publish it)


Nothing the first to share wisdom.