Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57650

sscanf starts to read from begining

int main(){
    int i,j;
    char *data = "1\n2\n";
    sscanf(data, "%d", &i);
    sscanf(data, "%d", &j);
    printf("i=%d, j=%d\n", i, j);
    return 0;
}

If you run the code you'll see this

i=1, j=1

Why j=1 here? Shouldn't it be 2? Am I missing something very basic?

If I use sscanf(data, "%d\n%d", &i, &j); it shows correct output. But now the next sscanf call will start reading from beginning again? Why is this? how to read it properly?

Upvotes: 0

Views: 333

Answers (1)

AusCBloke
AusCBloke

Reputation: 18492

Your two sscanf lines can be rewritten as:

sscanf("1\n2\n", "%d", &i);
sscanf("1\n2\n", "%d", &j);

It should be fairly obvious now why both i and j have the value 1. sscanf can't modify where data points.

Use a single sscanf call to extract both tokens instead:

sscanf(data, "%d\n%d", &i, &j);

Upvotes: 4

Related Questions