All submissions

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) {
    // Your logic here
    char *head, *tail;
    uint8_t i=0;
    head= (char *)str;
    tail= (char *)str;
    while ((*head) != '\0') {
        if ((*tail) == ',') {
            *tail = '\0';
            sscanf(head, "%uh", &arr[i]);
            i++;
            *count = i;
            *tail = ','; // restore the comma
            tail++;
            head=tail;
        } 
        else if ((*tail) == '\0') {
            sscanf(head, "%uh", &arr[i]);
            i++;
            *count = i;
            head= tail;  // ready to terminate it
        }
        tail++;
    }
}

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

scan string looking for comma. 

once found , temporarily replace it by a '\0' to read the portion of string

once read put back the comma and move on

until the real end char '\0' is found, then you read it and stop the iteration.

Loading...

Input

10,20,30

Expected Output

10 20 30