Search code examples
cparsinggcc

Parse string separated by commas and line breaks in C


I would like to parse a string that contains several line breaks, and each line is divided by commas, I would like to print each element separated by commas from each line. This is what I have tried, but it doesn't work.

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

int main() {
    char cadena[] = "10,Arbol,3.5\n20,Perro,4.0\n30,Mesa,4.5";
    char cadena_copy[sizeof(cadena)]; // Crea una copia de cadena
    strcpy(cadena_copy, cadena);

    char *linea = strtok(cadena_copy, "\n"); // Tokeniza la cadena por saltos de línea

    // Itera sobre cada línea
    while (linea != NULL) {
        char *token = strtok(linea, ","); // Tokeniza la línea por comas

        // Itera sobre cada valor en la línea
        while (token != NULL) {
            printf("%s\n", token); // Imprime el valor
            token = strtok(NULL, ","); // Obtiene el siguiente valor
        }

        linea = strtok(NULL, "\n"); // Obtiene la siguiente línea
    }

    return 0;
}

This is what I expect the output to be:

10
Arbol
3.5
20
Perro
4.0
30
Mesa
4.5

But instead I'm getting just the first line:

10
Arbol
3.5

How can I solve this?


Solution

  • Simply use both in the delimiter string

    int main() {
        char cadena[] = "10,Arbol,3.5\n20,Perro,4.0\n30,Mesa,4.5";
        char cadena_copy[sizeof(cadena)]; // Crea una copia de cadena
        strcpy(cadena_copy, cadena);
    
        char *token = strtok(cadena_copy, ",\n");
    
        // Itera sobre cada valor en la línea
        while (token != NULL) {
            printf("%s\n", token); // Imprime el valor
            token = strtok(NULL, ",\n"); // Obtiene el siguiente valor
        }
    
        return 0;
    }
    

    https://godbolt.org/z/fMv9evK7W