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