In C, the scanf()
function is used to read formatted data from the console.
The general syntax of scanf
is as follows:
int scanf(const char *format, Object *arg(s))
Object
: Address of the variable(s) which will store data
char *
: This contains the format specifiers
Format specifier is a special character which is used to specify the data type of the value being read.
Some of the frequently used specifiers are as follows:
If the function successfully reads the data, the number of items read is returned
In case of unsuccessful execution, a negative number is returned
If there is an input failure, EOF
is returned
#include <stdio.h>int main(){int a;float b;int x = scanf("%d%f", &a, &b);printf("Decimal Number is : %d\n",a);printf("Floating-Point Number is : %f\n",b);printf("Return Value: %d",x);return 0;}
Enter the input below
Note:
To use the
scanf()
function, thestdio.h
library must be includedThe
scanf()
function requires the address of the variable, not the actual variable itself. This is done to store the value at the memory location of the variable.
#include <stdio.h>int main(){char name[20];scanf("%s", &name);printf("Your name is: %s", name);return 0;}
Enter the input below
Note: In C, a
string
is the address of the character buffer which is why we do not need & with the variable.