views:

53

answers:

4

I was wondering whether there's a better way of doing this; say we read stdin to a string using fgets() where the string includes a total of n integers (e.g. 5 16 2 34 for n = 4), what would be the best way of extracting them? There has got to be a better way than this hack:

for (i=0, j=0; i<n; ++i, j+=pos)
     sscanf(string+j, "%d%n", &array[i], &pos); // Using %n makes me feel dirty

I know it's possible (and seemingly easier) to simply use something like for (i=0;i<n;++i) scanf("%d", array+i); but I'd rather avoid using scanf() for obvious reasons.¹

A: 

I'd say you might be better off using a regex library to do this, seeing as the amount is unknown

Necrolis
A: 

You could use strtok and strtol

MattSmith
A: 

What about first using strtok to tokenize the string and then use sscanf?

kgiannakakis
+1  A: 

You can use strtol. The following code reads exactly n integers from a string:

while (n)
  {
    int long v = strtol (s, &e, 10);
    if (v == 0 && strlen (e) > 0)
      {
        ++e;
        if (!e)
          break;
      }
    else
      {
        printf ("%d\n", v);
        --n;
      }
    s = e;
  }

This also works for ill-formed input like "5 16 4 blah blah 32".

Vijay Mathew