Home > Software design >  dynamically limit the number of chars considered in sscanf?
dynamically limit the number of chars considered in sscanf?

Time:05-11

(Context, thanks to the comments: I need to parse a substring of a longer string. The length of the substring isn't known until runtime, and the enclosing string is read-only, so writing a null terminator is out. Since it's on an embedded system, malloc() doesn't exist and stacksize is limited.)

Consider the following snippet, which limits the sscanf() conversion to the first two chars of "1234":

  int d;
  sscanf("1234", "-", &d);  // => 12

But what if you need to dynamically set that limit dynamically (e.g. for an input string that's not null terminated)? If it was analogous to printf(), you would be able to do this:

  int d;
  int len = 2;
  sscanf("1234", "%*d", len, &d);  // doesn't work

That doesn't work as expected, since the * modifier means to skip the next argument.

The best I've come up with is to use sprintf() to generate the format string for sscanf() dynamically:

  char fmt[5];
  int d;
  int len = 2;
  snprintf(fmt, sizeof(fmt), "%%           
  • Related