Alex Rivera | Logout

whitespace in the format string (scanf)

Asked 2012-10-11T08:32:46.007
14

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?

Edit
Report

1 Answer

8

If you want to accept 1c2 but not 1 c 2, use the pattern without the space:

scanf("%dc%d", &x, &y);

If you want to accept 1c2 and 1 c 2 (and also 1 \t \t c \t 2 etc), use the pattern with the space:

scanf("%d c %d", &x, &y);

If you want to accept 1 c 2 but not 1c2, add a fake string containing whitespace:

scanf("%d%*[ \t]c%*[ \t]%d", &x, &y);

Here the format string %[ \t] would mean "read a string that contains any number of space and tab characters"; but using the additional *, it becomes "expect a string that contains any number of space and tab characters; then discard it"

answered 2012-10-11T09:56:11.990

Your Answer