sscanf strings

Started by
2 comments, last by fractoid 19 years, 4 months ago
I'm trying to sscanf a string from a buffer, this string is inclosed within a pair of " The output should be the same as buffer: CODE: char buffer[600]; buffer = "8 10000 \"Pistol\" \"Basic Weapon\nLow Fire Rate\" weapons/pistol.bmp 255 0 255 1000 25 5"; unsigned int clipsize, maxammo, reload, firerate; char name[20], description[256]; char* iconfile; int r, g, b; int damage; sscanf(buffer, "%d %d %s %s %s %d %d %d %d", &clipsize, &maxammo, name, description, iconfile, &r, &g, &b, &reload, &firerate, &damage); printf("%d %d \"%s\" \"%s\" %s %d %d %d %d", clipsize, maxammo, name, description, iconfile, r, g, b, reload, firerate, damage);
Advertisement
  • You can't assign a string literal to an array like that. An array has, unlike a pointer, a fixed address. The assignment is trying to change that address to that of the string literal.

  • You didn't allocate memory for *iconfile - your code will crash.

  • scanf treats whitespace as separators. Like it or not, %s will only ever read a single 'word'.

  • What you really want is to use a scanset, associated with character anchors:
    "%d %d \"%[^\"]\" \"%[^\"]\" %s %d %d %d %d %d %d". Refer to your C library documentation for more details.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Thanks Fruny
sscanf = time * money

As an interesting corollary,
girls = buffer overflow.

Also, there's some flag you can give to sscanf that causes it to not treat whitespace as a delimiter, but I can't remember what it is. Regardless, sscanf is prone to buffer overflows and general badness - I'd consider using a std::stringstream and << >> operators.

This topic is closed to new replies.

Advertisement