Commonly used scanf format codes in C
In C programming language, we use scanf
to take input from users in command line. When taking input, we need to use some flag, that we call ‘format codes’ for scanf
.
Lets see an example C program where take input from user using the scanf
. So declared a variable of int
type and used printf
to prompt user to enter his/her age. Then in the next line, we used scanf
. In scanf
we use a code or flag to indicate which type of input we are taking, and in which variable we want to store the input
In the following example, we used the format code %d
that we use for integer. We wanted to keep the input in the variable age
, so we used &age
//Link to code: https://onlinegdb.com/S1FfbhyVP
#include <stdio.h>
int main()
{
int age;
printf("Enter your age\n");
scanf("%d", &age);
printf("Your age is %d", age);
return 0;
}
Here is a list different format codes for the scanf
command with their purposes.
Code | Purpose |
%c | read a single character |
%d | read a decimal integer |
%e | read a floating point value |
%f | read a floating point value |
%g | read a floating point value |
%h | read a short integer |
%i | read decimal, hexadecimal or octal integer |
%o | read an octal integer |
%s | read a string |
%u | read an unsigned decimal integer |
%x | read a hexadecimal integer |
%[….] | read a string of word(s) |