Extract an unspecified number of integers from a string

I was wondering if there is a better way to do this; let's say we read stdin for a string using fgets(), where the string contains a total of integers n(for example, 5 16 2 34for n = 4), what would be the best way to extract them? There should 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 that it is possible (and seemingly simpler) to just use something like for (i=0;i<n;++i) scanf("%d", array+i);, but I would prefer not to use it scanf()for obvious reasons. ยน

+3
source share
4 answers

strtol. n :

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

, "5 16 4 blah blah 32".

+2

, regex ,

0

You can use strtok and strtol

0
source

How to use strtok first to tokenize a string and then use sscanf?

0
source

Source: https://habr.com/ru/post/1767119/


All Articles