I'm programming C using Linux gcc with -std=c89
switch. I have a variable storing a string such as:
10, 1, 2, 3
I've shown 4 integers in the above string, but the real number isn't known ahead of time. How can I extract these values into an integer array? We can allocate the memory using an upper bound of say, 8, for example. But the actual number of integers will always be <= 8.
Currently, I'm doing the following:
sscanf(csv_variable, "%i,%i,%i,%i,%i,%i,%i,%i",
&int_variable[0],
&int_variable[1],
&int_variable[2],
&int_variable[3],
&int_variable[4],
&int_variable[5],
&int_variable[6],
&int_variable[7]);
but this works for input strings having 8 integers. Would like to have the parsing done inside a loop somehow so it can accomodate any number up to, for example, 8 possible integers (so that it works for cases where less than 8 integers are provided).
Just check the return from sscanf
to find out how many were read successfully:
int values_read = sscanf(csv_variable, "%i,%i,%i,%i,%i,%i,%i,%i",
&int_variable[0],
&int_variable[1],
&int_variable[2],
&int_variable[3],
&int_variable[4],
&int_variable[5],
&int_variable[6],
&int_variable[7]);
if you want to do it in a loop you can tokenize the string using strtok
char *tok = strtok(csv_variable, ",");
int i = 0;
while(tok != NULL) {
int_variable[i] = atoi(tok);
i++;
tok = strtok(NULL, ",");
}
Though at a higher level, you really should think twice before using strtok. It is deprecated, non-reentrant and widely consider to be one of the worst designed function in the C standard library.
http://stackoverflow.com/questions/7100214/strtok-segfault Would my application be better suited perhaps (?) - ggkmath 2012-04-04 22:49
strtok
modifies the original string and can fault if the string is constant. You probably should create a copy, that isn't constant, of the string to preserve the original string - twain249 2012-04-04 22:54
Consider using the function strtok. It takes to strings, one with the data, and the other with the delimiter. It returns a pointer to the token, so you just have to loop until a NULL is returned. There is an example of this at http://www.elook.org/programming/c/strtok.html.
You just need to change the loop to have a counter and then index into your array. You may also want to check the number of items against the number you can hold in your array to prevent overflowing your array and overwriting some memory.