c++cscanf

Check scanf formating without conversions


Is there a way how to check if some specific characters were given on input using scanf without using character conversions?

int main(void)
{
if(scanf("{ ["))
    printf("GOOD INPUT\n");
else
    printf("BAD INPUT\n");
return 0;
}     

This code always gives the bad input option (it expects scanf return value to be 1) but interestingly if I enter other than the desired characters it gives the bad input imediately but if I enter it as its specified in the scanf it blows the bad input at me AFTER I enter the whole input.

So it must be awaiting the input to be in that specified format but my question is: How can I check it, without any conversions, and make according action depending on wether the input was entered correctly or not?


Solution

  • scanf (and cousins) returns a count of the number of successful conversions. If you specify 0 conversions, then its return value will always be 0.

    To use scanf for this task, I'd probably use a couple of scanset conversions:

    char a[2], b[2];
    if (scanf("%1[{] %1[[]", &a, &b) == 2)
        printf("Matched");
    

    Or, you could simplify this a little bit:

    char a[2];
    if (scanf("{ %1[[]", &a) == 1)
    

    Either way, we've specified each scan set to match only one specified character, but it's still a conversion, so we can see whether it succeeded or failed.

    Unfortunately, we still have to assign the result somewhere. scanf does support using * like this: "%*s", to tell it to read a string, but not store the result anywhere--but when you do so, that conversion doesn't get counted in the return value, so (much like before) we can't use it to determine whether we got a match or not.