Search code examples
cc89

Get numbers separated by commas


I got the following string:

"312 ,22 ,+12 , -12 , 5331"

it is possible to have more than 1 space between numbers.

I need to convert it to an array like that:

int arr[] = {312,22,-12,12,5331};

Is there a pretty and elegant way to do this with C89?


Solution

  • Use strtok + atoi:

    # include <stdio.h>
    # include <stdlib.h>
    # include <string.h>
    
    int main(int argc, char const *argv[])
    {
        char numbers_str[] = "312 ,22 ,+12 ,-12 ,5331", *currnum;
        int numbers[5], i = 0;
    
        while ((currnum = strtok(i ? NULL : numbers_str, " ,")) != NULL)
            numbers[i++] = atoi(currnum);
    
        printf("%d\n", numbers[3]);
        return 0;
    }