I am a newbie when it comes to c++, what I am trying to do is read from .csv file and and store it in vectors and then to be displayed, my problem is that the code crashes after the last reqd entry is displayed from the file when running from terminal, but in ide (codeblocks) it says sigsegv error when I try to debug it…
ps: the reason I want the read the file into vectors is to be able to enter into mysqldb later
#include <vector>
#include <string>
#include <sstream>
#include<fstream>
#include <iostream>
using namespace std;
vector<string> split_at_commas(const string& row)
{
vector<string> res;
istringstream buf(row);
string s;
while (getline(buf, s, ','))
res.push_back(s);
return res;
}
int main()
{
string line;
ifstream data("Book1.csv" ,ios::out);
while(!data.eof())
{
getline(data,line,'\n');
vector<string> v = split_at_commas(line);
/*ide points error to this line*/
cout << v[0] << '\t' << v[1] <<'\t' << v[2]<< '\t'<<endl;
}
data.close();
}
There is no guarantee that ‘v’ holds three or more elements. Check the content of ‘v’ after the call to split_at_commas and before the print in a debugger to verify that v holds 3 or more items.