Search code examples
cstringcsvquotation-marks

How to parse a .csv file with quotation marks in C


Lets say the string im trying to parse reads

"Smith, John",Data1,Data2,Data3

I could also get lines that read

Dave, Data1,Data2,Data3

so I have the if statement

line is the line of text fgets()'d from the file, but I think that works

The rest I've been struggling with for about an hour or so now. I'm trying to reformat the "Smith, John" so its John Smith, then assign it to recTemp.artist

if (line[0] == '\"') {
    //Read the last name, first name",
    char lastTemp[30] = "";
    char firstTemp[30] = "";
    strcpy(lastTemp , strtok(line, ", "));
    strcpy(firstTemp, strtok(NULL, "\","));
    char * t;
    t = strstr(lastTemp, "\"");
    strcpy(t, " ");
    //Concatenate each string assign to the artist value
    strcat(firstTemp, lastTemp);
    strcpy(recTemp.artist, firstTemp);
}

I think the error comes from the strstr call or the strcpy right after it, but I'm not sure

Thanks!


Solution

  • To answer your question:

    "I'm trying to reformat the "Smith, John" so its John Smith"

    Short of using regular expressions to extract the quotations out of the string, I would do the following,

    #include <iostream>
    #include <cstring>
    #include <stdio.h>
    
    int main() {
        char line[100] = "\"Smith,John\",Data1,Data2,Data3";
        // fgets(line, 100, stdin);
        char* name = strtok(line, "\"");
        char *substring2 = strtok(NULL, "\"");
        char* LastName = strtok(name, ",");
        char* FirstName = strtok(NULL, ",");
    
        char result[100];
        strcpy(result, FirstName);
        strcat(result, ",");
        strcat(result, LastName);
        strcat(result, substring2);
        printf("%s",result);
    
    }
    

    which produces the output:

    John,Smith,Data1,Data2,Data3