I have been struggling with the whole line(\n or \r) thing, i was assigned myself a task to read a .csv file that contains 4K lines in it..with my curiosity i have found the way to read the csv file and separate each field/word from the delimiter ','.
std::istream& safeGetline(std::istream& is, std::string& t)
{
t.clear();
std::istream::sentry se(is);
std::streambuf* sb = is.rdbuf();
for(;;) {
int c = sb->sbumpc();
switch (c) {
case '\r':
if(sb->sgetc() == '\n')
sb->sbumpc();
return is;
case EOF:
// Also handle the case when the last line has no line ending
if(t.empty())
is.setstate(std::ios::eofbit);
return is;
default:
t += (char)c;
}
}
}
int main()
{
cout<<"Enter the file path :";
string filename;
cin>>filename;
ifstream file;
file.open(filename.c_str(),ios::in);
vector<string>arr;
string content;
string arr2;
stringstream ss;
// sqlite3 *db;int rc;sqlite3_stmt * stmt;
int i=0;
while (!safeGetline(file,content).eof())--here is the problem
{
ss<<content;
//since some of the field content falls next line i have decided to remove the '\n'
content.erase(std::remove(content.begin(), content.end(), '\n'), content.end());
while (getline(ss,arr2,','))
{
arr.push_back(arr2);
}
}
}
here this while (!safeGetline(file,content).eof())--i thought this code will read the first line from the CSV file and gone through while (getline(ss,arr2,',')) for delimiter seperation,but what happenning is that the safeGetline() as well as the normal getline()--which i tried before instead of safeGetline() read the entire content and come through the delimiter seperation part this makes me hard to insert those fields in the DB
ex:
4xxxxxx,"field2",field3,,,,field7
400x1x2,"field2",,field4,,,field7
After the code start read, The while (!safeGetline(file,content).eof()) returns
output:
4xxxxxx,"field2",field3,,,,field7400x1x2,"field2",,field4,,,field7
Here the field7 and the value 400x1x2 which was present at the second line got combined field7400x1x2--this gives bogus result when i insert those fields into my table(i.e) values are cluttered improperly inside the table.
So how could i really perform line by line read operation(i.e) in my case read->seperate delimeter->push to vector->insert to table->second read->.....
Aucun commentaire:
Enregistrer un commentaire