Parse Comma-Separated Integers into an Array

Code

#include <stdio.h>
#include <stdint.h>
void parse_csv_to_array(const char *str, uint8_t *arr, uint8_t *count) 
{
    int i,j,k,c=0;
    for(i=0,k=0;str[i];i++)
    {
        int sum=0;
        for(j=i;str[j]!=',' && str[j]!='\0';j++)
        {
            if(str[j]>=48 && str[j]<=57)
            {
                sum =(sum*10)+(str[j]-'0');
                c++;
            }
        }
        if(c>0)
        {
            arr[k]=sum;
            (*count)++;
            k++;
            c=0;
            i=j;
        }
    }
}
int main() 
{
    char str[101];
    fgets(str, sizeof(str), stdin);
    uint8_t i = 0;
    while (str[i]) {
        if (str[i] == '\n') {
            str[i] = '\0';
            break;
        }
        i++;
    }
    uint8_t arr[20];
    uint8_t count = 0;
    parse_csv_to_array(str, arr, &count);
    for (uint8_t i = 0; i < count; i++) 
    {
        printf("%u", arr[i]);
        if(i < count - 1)
        {
            printf(" ");
        }
    }
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

10,20,30

Expected Output

10 20 30