Sign in to follow this  

sscanf strings

This topic is 4748 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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);

Share this post


Link to post
Share on other sites
  • 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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

This topic is 4748 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this