How to read data using scanf() in C
In C, the scanf() function is used to read formatted data from the console.
Syntax
The general syntax of scanf is as follows:
int scanf(const char *format, Object *arg(s))
Parameters
-
Object: Address of the variable(s) which will store data -
char *: This contains the format specifiers
Format Specifier
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:
- s - strings
- d – decimal integers
- f – floating-point numbers
- c – a single character
Return value
-
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,
EOFis returned
Code
1. Reading an integer and a floating point value
#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.hlibrary 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.
2. Reading a string
#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
stringis the address of the character buffer which is why we do not need & with the variable.
Free Resources