By using ‘*’ before the format specifier, we can tell scanf to skip whitespace characters.
For example, consider the following program:
#include <stdio.h>
int main()
{
int n;
char c;
scanf("%d%c", &n, &c);
printf("n = %d and c = %c", n, c); return 0;
}
Let’s say the inputs are “10 A” (without quotes). Then, the output will be
10 A
n = 10 and c =
The variable c is not empty; it is holding the whitespace character.
Now, to skip reading the whitespace characters, we can include the format specifier %*c
before the format specifier %c
as follows:
#include <stdio.h>
int main()
{
int n;
char c;
scanf("%d%*c%c", &n, &c);
printf("n = %d and c = %c", n, c); return 0;
}
Output:
10 A
n = 10 and c = A
Alternatively, we can add a whitespace between %d and %c as follows:
#include <stdio.h>
int main()
{
int n;
char c;
scanf("%d %c", &n, &c);
printf("n = %d and c = %c", n, c); return 0;
}
Output:
10 A
n = 10 and c = A
Leave a comment