From the man page of scanf:
A directive is one of the following:
A sequence of white-space characters (space, tab, newline, etc.; see isspace(3)). This directive matches any amount of white space, including none, in the input.
An ordinary character (i.e., one other than white space or '%'). This character must exactly match the next character of input. (emphasis mine)
A conversion specification, which commences with a '%' (percent) character. A sequence of characters from the input is converted according to this specification, and the result is placed in the corresponding pointer argument. If the next item of input does not match the conversion specification, the conversion fails—this is a matching failure.
Now, consider the following code:
#include <stdio.h>
int main(void)
{
const char* fmt = "A %49s B";
char buf[50];
printf("%dn", sscanf("A foo B", fmt, buf)); // 1
printf("%dn", sscanf("blah blaaah blah", fmt, buf)); // 0
printf("%dn", sscanf("A blah blah", fmt, buf)); // 1
retu 0;
}
Lines 1 and 3 print 1 because matching "A" with "A" succeeds, as does matching "foo"/"blah" with %s. Line 2 prints 0 because "A" caot be matched with "blah", so parsing stops there.
This is all fine and logical, but is there any way for me to detect that a matching failure occurred after all conversion specifications have been successfully matched and assigned? In that case, the value retued by scanf will be the number of conversion specifiers in my format string, so I can't use it to tell if matching succeeded till the very end.
In other words: the string fed to sscanf in line 3 is not "valid" in the sense that it's not in the format A [something] B. Can I use scanf to detect this, or is strtok my only option?
