Parse Comma-Separated Integers into an Array

Code

#include <stdio.h>
#include <stdint.h>
#include<string.h>
void parse_csv_to_array(const char *str, uint8_t *arr, uint8_t *count) {
  int n=strlen(str);
  int k=0,v=0,got_digit=0;
  for(int i=0;i<n;i++)
  {
    if(str[i]>='0'&& str[i]<='9')
    {
        v=v*10+str[i]-'0';
        got_digit=1;
    }
    else{
        if(got_digit){
        arr[k++]=v;
        v=0;
        got_digit=0;}
    }
  }
  if(got_digit)
  arr[k++]=v;
  *count=k; 
}

int main() {
    char str[101];
    fgets(str, sizeof(str), stdin);

    // Remove newline
    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