0

I have a code that reads a file with a following: word1,word2,word,3....,word8 word1,word2,word,3....,word8 word1,word2,word,3....,word8

ifstream infile;
    //string path;s
    infile.open("file.csv");
    string line;
    CourseNode *current = head;
    int i=1;
    if(infile.is_open()){  
    while(getline(infile, line)) { 
        if(i == 1)
            cout << "1st line==> "+line << endl;  // ignore first line
        else {    // read data
        string firstname, lastname, id, a,b,c,d,t ;
        stringstream sst(line); 
        getline(getline (sst, firstname, ','),lastname, ',');
        //getline(getline(getline (sst, firstname, ','),lastname, ','),id, ','); 
        cout << "result==> "<< firstname<<" "<<lastname << endl;
    }  
    i++;
    }

I assume i have to work with this line and insert there my string variables but i am not sure how! getline(getline (sst, firstname, ','),lastname, ',');

Any help will be appreciateed! Thank you!

Fantom
  • 1
  • 2
  • There are so many ways to split a string based on a delimiter - see https://stackoverflow.com/questions/14265581/parse-split-a-string-in-c-using-string-delimiter-standard-c – Support Ukraine Oct 05 '20 at 12:57

1 Answers1

0

To read a .csv file you may read the entire line and split after to load easly your data:

std::ifstream infile;
infile.open("file.csv");
std::string line;
int i = 1;

if(infile.is_open()){  
    while(getline(infile, line)) { 
        if(i == 1) {
            // ignore line
            continue;
        } else {    // read data
            std::vector<std::string> value; // this is where you stock the data
            value = split(line); // add your implementation of split
            // here: do something with the data in value
        }
        i++;
    }
}

You have in value every data from a line of your .cvs file. Now, you can assigne every case to a specific variable or put them in a list of object.

DipStax
  • 343
  • 2
  • 12
  • Thank you! but can you write code fully if you can, i did not study vector and not sure about some things in your code – Fantom Oct 05 '20 at 13:24
  • You don't know how to use vector or you can't use it? And do you wan't a split function example? – DipStax Oct 05 '20 at 14:16