I have a following problem. I want to convert a string like "10 15 30" to an int array with ints 10, 15, 30. I searched in google a lot, but usually solutions included vectors (which I am not familiar with) or other more complex solutions. I found a code like this:
#include <cstdio>
void foo ( char *line ) {
int num, i = 0, len;
while ( sscanf( line, "%d%n", &num, &len) == 1 ) {
printf( "Number %d is %d; ", i, num );
line += len;
i++;
}
}
int main ( ) {
char test[] = "12 45 6 23 100";
foo( test );
return 0;
}
It works and extracts numbers from string in a way I wanted, but I don't understand part with:
line += len;
Can someone explain how it works? Why are we adding len (which is int) to the string?
line += len;is called this pointer is incremented by the number of characters that were read by sscanf. (if I'm understanding the behavior of%n). So the next time you call sscanf the pointer line points to the the position of next number in the string.but usually solutions included vectors (which I am not familiar with)You should start getting familiar with it. Might as well start now. And how was this code "simpler" than the answer given by @zenith? Your code is not really intuitive, not typesafe, and even an experienced programmer has to read the docs or look twice (or more times) at it to figure out what it is doing.