ggkmath
ggkmath

Reputation: 4246

C Program: how to parse csv string using a loop?

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).

Upvotes: 1

Views: 1604

Answers (3)

twain249
twain249

Reputation: 5706

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, ",");
}

Upvotes: 5

Glenn
Glenn

Reputation: 1167

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.

Upvotes: 1

Jerry Coffin
Jerry Coffin

Reputation: 490148

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]);

Upvotes: 2

Related Questions