Parse Comma-Separated Integers into an Array

Code

#include <stdio.h>
#include <stdint.h>
#include <string.h>


void parse_to_array(char* str, uint8_t *arr, int* count){
    int i = 0; 
    while(str[i] != '\0'){
        if(str[i] == ','){
            (*count)++;
            i++;
        }
        arr[*count] = arr[*count]*10 + (str[i] - '0');
        i++;
    }
}

int main(){
    char str[101];
    fgets(str, sizeof(str), stdin);
    str[strcspn(str,"\n")] = '\0';
    
    uint8_t arr[20] = {0};
    int count = 0;
    parse_to_array(str, arr, &count);

    for(int 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