Jamie Jamie - 26 days ago 7
C Question

What's wrong with this sscanf() format string?

I'm trying to parse a simple string: a character from the set "rgbcmyw" followed by a character form the set "slh" then an integer.

risk:9008:~$ cat test-scanf.c
#include <stdio.h>

int main(int argc, char ** argv) {
char c,m;
int s;

printf("Scanned %d elements.\n", sscanf(argv[1], "%[rgbcmyw]%[slh]%d", &c, &m, &s));
printf("Scanned:\n\tc = %c (%d)\n\tm = %c (%d)\n\ts = %d\n",c,c,m,m,s);

return 0;
}
risk:9012:~$ gcc test-scanf.c && ./a.out rs40
Scanned 3 elements.
Scanned:
c = (0)
m = s (115)
s = 40
risk:9013:~$


Why is zero being assigned to 'c'?

EDIT: The solution

One needs space for the character being scanned plus a
nul
termination:

#include <stdio.h>

int main(int argc, char ** argv) {
char c[2],m[2]; /* Need space for the character *and* the 'nul' termination. */
int s;

printf("Scanned %d elements.\n", sscanf(argv[1], "%[rgbcmyw]%[slh]%d", c, m, &s));
printf("Scanned:\n\tc = %s\n\tm = %s\n\ts = %d\n",c,m,s);

return 0;
}

Answer

Your code is passing the wrong type of parameters to sscanf(). The "%[] specifier expects a char * pointer.

Comments