Consider the following code:
#include<stdio.h>
int main() {
int i=3, j=4;
scanf("%d c %d",&i,&j);
printf("%d %d",i,j);
return 0;
}
It works if I give 2c3
or 2 c 3
or 2c 3
as input if I have to change the value of variables. What should I do if I want the user to enter the same pattern as I want means if %dc%d
then only 2c3
is acceptable and not 2 c 3
and vice versa if it is %d c %d
?
Whitespace in the format string matches 0 or more whitespace characters in the input.
So "%d c %d"
expects number, then any amount of whitespace characters, then character c
, then any amount of whitespace characters and another number at the end.
"%dc%d"
expects number, c
, number.
Also note, that if you use *
in the format string, it suppresses assignment:
%*c
= read 1 character, but don't assign it to any variable
So you can use "%d%*c c%*c %d"
if you want to force user to enter: number, at least 1 character followed by any amount of whitespace characters, c
, at least 1 character followed by any amount of whitespace characters again and number.