2

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.

Michael Kohne
  • 11,888
  • 3
  • 47
  • 79
Ethan
  • 1,206
  • 3
  • 21
  • 39

2 Answers2

4

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:");
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
2

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.

001
  • 13,291
  • 5
  • 35
  • 66