manipulate csv file in c ++

0

I need to read a cvs file with the following fields:

Id,OwnerUserId,CreationDate,Score,Title,Body    

Id    inteiro  
OwerUserID    inteiro  
Data     vou armazerna como char    
Score     inteiro  
Title      texto  
Body       texto 

Example of a line (there are many lines):

469, 147, 2008-08-02T15:11:16Z, 21, How can I find the full path to a font from its   display name on a Mac?, "Iam using the Photoshop's.......</ul> "  

These ..... in the body field was to shorten, because the text size is much larger

and store in a vector of structs of type:

struct Questions {

    int id;  
    int ownerUsedId;  
    char creationDate[30];  
    int score;
    char title[100];
    char body[200];

}; 

For this I did the following function:

void loadQuestions( fstream &file, Questions *questions)
{
    string registro;



    getline(file, registro);


    char *buffer =new char[500];
    char *ptr;

    getline(file, registro); 
    strcpy(buffer, registro.c_str());  



    ptr = strtok(buffer, ",");
       cout << atoi(ptr) << "   ";// pega o campo id

    ptr = strtok(NULL, ",");
       cout << atoi(ptr) << "    ";// pega o campo ownerUsedId

    ptr = strtok(NULL, ",");// pega o campo data
       cout << (ptr) << "    ";

    ptr = strtok(NULL, ",");// pega o campo score
       cout << atoi(ptr) << "    ";



} // mostrei na tela para ver se o programa tava certo, nao armazenei ainda na struct  

Until the fourth comma has worked out, I am separating by comma, but the problem arises: in the title or body field a comma can appear in the middle of the text, forcing strtok to this point, with that messed up all the reading .

Question: how to store each field correctly in my struct, since in the body and tittle field can appear several commas, one thing I noticed was that the Body field starts and ends with quotation marks ("") how to delimit to copy this field, but within the body field (which is a text) there may be quotation marks ("")
How can I copy each of these fields correctly?

    
asked by anonymous 16.03.2018 / 22:09

1 answer

0

You can use a composite approach. Until the fourth field you use strtok, from then on you make a for looking for the first occurrence of quotation marks (beginning of Body), everything that has joined until there is Title and from there until the end is Body. >     

16.03.2018 / 22:29