开发者

Extract an undetermined number of integers from a string

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 w开发者_开发问答ay 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.¹


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".


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


You could use strtok and strtol


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜