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?
Your two
sscanflines can be rewritten as:It should be fairly obvious now why both
iandjhave the value1.sscanfcan’t modify wheredatapoints.Use a single
sscanfcall to extract both tokens instead: