sscanf wrapping function to advance string pointer in C

Posted by Dusty on Stack Overflow See other posts from Stack Overflow or by Dusty
Published on 2010-03-17T00:11:04Z Indexed on 2010/03/17 0:21 UTC
Read the original article Hit count: 312

Filed under:
|
|

I have a function that makes a series of calls to sscanf() and then, after each, updates the string pointer to point to the first character not consumed by sscanf() like so:

if(sscanf(str, "%d%n", &fooInt, &length) != 1)
{ 
   // error handling
}
str+=length;

In order to clean it up and avoid duplicating this several times over, i'd like to encapsulate this into a nice utility function that looks something like the following:

int newSscanf ( char ** str, const char * format, ...)
{
  int rv;
  int length;
  char buf[MAX_LENGTH];
  va_list args;

  strcpy(buf, format);
  strcat(buf, "%n");
  va_start(args, format);
  rv = vsscanf(*str, buf, args, &length);
  va_end(args);
  *str += length;

  return rv;
}

Then I could simply the calls as below to remove the additional parameter/bookkeeping:

if(newSscanf(&str, "%d", &fooInt) != 1)
{ 
   // error handling
}

Unfortunately, I can't find a way to append the &length parameter onto the end of the arg list directly or otherwise inside newSscanf(). Is there some way to work around this, or am I just as well off handling the bookkeeping by hand at each call?

© Stack Overflow or respective owner

Related posts about c

    Related posts about sscanf