Search code examples
c++csvfstream

read csv file in c++ and store in different variable


I need to read a file which is similar to a CSV file (the first line is just different of the rest of the text).

the file is structured like that, the first line and after each line contains a firstname and a name:

first line
Barack Obama
Jacques Chirac
John Paul-Chouki
etc.

I need to store the name and the first name different variable using getline:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {


    //open file with ifstream (with full path)
    ifstream file("file.txt");
    string line;
    string lineContent;
    string firstname;
    string name;
    int i=1;


    //check if file is really open
    if ( ! file.is_open() ) {
        cout <<" Failed to open" << endl;
    }
    else {
        cout <<"Opened OK" << endl;
    }

    while(file >> line) {
        if(i == 1)
            cout << "1st line==> "+line << endl;
        else
            getline(file,line, ' ');
            cout << "result==> "+line << endl;
        i++;
    }
}

for now it doesn't work.


Solution

  • The promblem is that file >> line and getline(file,line, ' ') both read the file.

    Try rather:

    ...
    while(getline(file,line)) {
        if(i == 1)
            cout << "1st line==> "+line << endl;  // ignore first line
        else {    // read data
            string firstname, lastname;
            stringstream sst(line); 
            sst >> firstname >> lastname; 
            cout << "result==> "<< firstname<<" "<<lastname << endl;
            // where to store the data ? 
        }  
        i++;
    }
    

    It's not clear where you have to store the data. So complete the code to add the first and last names to an array, or better, a vector.

    Edit:

    Note that your sample data is not in CSV format: CSV means Comma Separated Values. If data was to be separated by commas, you could relplace the sst>>... line with

        getline(getline (sst, firstname, ','),lastname, ',');