Reputation: 1266
So I'm wondering how sscanf functions when faced with a line like this:
sscanf(input_string, "%s %s %s", cmd1, cmd2, cmd3);
But say the input_string only contains 1 string token. What values are assigned to cmd2 and cmd3? Is there an error thrown?
I'm using the GNU C compiler.
Upvotes: 2
Views: 932
Reputation: 490158
Nothing will be assigned to the extra parameters. The return from sscanf
tells you how many conversions were done successfully, so in this case it would return 1
. You typically just compare to the number you expect, and assume the input is bad otherwise:
if (3 != sscanf(input_string,"%s %s %s", cmd1, cmd2, cmd3))
fprintf(stderr, "Badly formatted input (expecting three strings)\n");
When you're reading from a file, you often want to execute in a loop until you get correct input:
while (3 != scanf("%s %s %s", cmd1, cmd2, cmd3))
fprintf(stderr, "Please enter 3 strings:");
Upvotes: 4
Reputation: 13533
http://www.cplusplus.com/reference/clibrary/cstdio/sscanf/
On success, the function returns the number of items in the argument list successfully filled. This count can match the expected number of items or be less -even zero- in the case of a matching failure. In the case of an input failure before any data could be successfully interpreted, EOF is returned.
Upvotes: 2