mohit
mohit

Reputation: 6044

parse string input using sscanf iteratively

I've an input string consisting of space separated numbers like "12 23 34".
Output should be an array of integers.

I tried the following:

while (sscanf(s, "%d", &d) == 1) {
    arr[n++] = d;
}

But I found that since I'm not reading from file (where offsets are adjusted automatically),
I keep storing the same number in d everytime.

Then I tried this:

while (sscanf(s, "%d", &d) == 1) {
    arr[n++] = d;
    s = strchr(s, ' ');
}

to manually shift s to a new number.
Which I believe should work fine. I simply don't understand why it fails.

Upvotes: 2

Views: 826

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726609

The second trick should indeed work with minor modifications. See comments in the code for explanation of what needs to change:

while (sscanf(s, "%d", &d) == 1) {
    arr[n++] = d;
    s = strchr(s, ' ');
    // strchr returns NULL on failures. If there's no further space, break
    if (!s) break;
    // Advance one past the space that you detected, otherwise
    // the code will be finding the same space over and over again.
    s++;
}

A better approach to tokenizing sequences of numbers is strtol, which helps you advance the pointer after reading the next integer:

while (*s) {
    arr[n++] = strtol(s, &s, 10);
}

Upvotes: 2

user2404501
user2404501

Reputation:

scanf provides an elegant answer: the %n conversion, which tells you how many bytes have been consumed so far.

Use it like this:

int pos;
while (sscanf(s, "%d%n", &d, &pos) == 1) {
    arr[n++] = d;
    s += pos;
}

Upvotes: 5

Related Questions