Home »
C programs »
C scanf() programs
Input individual characters using scanf() in C
Here, we are going to learn how to input individual characters using single scanf() function in C programming language?
By IncludeHelp Last updated : March 10, 2024
Input individual characters using scanf()
To understand the functionally of scanf() while reading characters, we need to understand its flow, Consider the following statement:
scanf ("%c%c%c", &x, &y, &z);
Now, if the input is "a b c", then 'a' will be assigned to variable x, SPACE will be assigned to variable y and 'b' will be assigned to variable z.
Thus, scanf() reads the characters as well as space, tab and new line character.
So to read character values after skipping spaces, tabs we need to skip any value between two character values and this is possible by using skip format specifier "%*c".
Without skipping spaces between characters
#include <stdio.h>
int main(void)
{
char x;
char y;
char z;
//input
printf("Enter 3 character values: ");
scanf ("%c%c%c", &x, &y, &z);
//print
printf("x= \'%c\' \n", x);
printf("y= \'%c\' \n", y);
printf("z= \'%c\' \n", z);
return 0;
}
Output
Enter 3 character values: a b c
x= 'a'
y= ' '
z= 'b'
Here, x contains 'a', y contains ' ' (space) and z contains 'b'.
By skipping spaces or any character between characters
#include <stdio.h>
int main(void)
{
char x;
char y;
char z;
//input
printf("Enter 3 character values: ");
scanf ("%c%*c%c%*c%c", &x, &y, &z);
//print
printf("x= \'%c\' \n", x);
printf("y= \'%c\' \n", y);
printf("z= \'%c\' \n", z);
return 0;
}
Output
Enter 3 character values: a b c
x= 'a'
y= 'b'
z= 'c'
C scanf() Programs »