1

I have a data, which is seperated by "," and I have 7 lines of that. I am trying to read the data seperated by comma into 2d vector like this:

ifstream input;
input.open("wordplate.csv");
vector<vector<string>> data;
string line;
while(getline(input,line)){
    cout<<"A\n";
    stringstream ss(line);
    string value;
    vector<string> record;
    while(getline(ss,value,',')){
        record.push_back(value);
    }
    data.push_back(record);
}

input.close();

But for some reason, I am getting only the last line of my csv file. What am I doing wrong here?

  • That works as expected, I get all lines. How do you print it? – Maxim Egorushkin Jan 11 '18 at 12:56
  • It shows, that my vector data has a size of 1 and data[0] has a size of 109, seems that it pushed back everything into data[0] –  Jan 11 '18 at 12:59
  • On my machine, it processed 9 records with that data. I suspect your line endings in your wordplate.csv file are incorrect for your platform. – Eljay Jan 11 '18 at 13:07

2 Answers2

0

Could you provide real data? I just tested this code in Visual Studio 2015 and it seems to work.

Maybe reading answers here can help you: How can I read and parse CSV files in C++?

wdudzik
  • 1,264
  • 15
  • 24
  • You can have a look at the data –  Jan 11 '18 at 13:01
  • I meant if you can provide the file which you are reading. Also it seems that line endings are wrong for your OS ( e.g. in windows it should be \r\n and on unix \n) – wdudzik Jan 11 '18 at 14:21
0

This is how I print the result:

for(auto const& r : data) {
    for(auto const& c : r)
        std::cout << c << ' ';
    std::cout << '\n';
}

And it shows that your code reads all csv lines as expected.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271