C++ read csv file row into vector
Hello,
I was wondering what would be the easiest way in c++ to read a line from a csv file; each row of the file starts with a string and follows with a variable number of numeric (double), ';' separated values. I'd like to read the string into a string variable and the doubles into a vector. Thanks for your help. |
look up strtok, and strtok_r for threaded programmings. I'll tell you now that it's a slightly confusing command. If you need help with it, just ask. Untill then i'll let you use the million docs written on it.
|
Thanks karlan. I think I can handle the string-splitting part even without strtok. What I don't like though, is the whole loop concept
(lines 18 - 22 of the code dump below) - is it really necessary?. I wonder if something like vector <double> d; is >> d; could work instead of the while loop - or would I have to take care of the '>>' operator overloading myself? Thanks again. This is the best I could come up with so far: 1 string rowhead; 2 double dval; 3 string row; 4 vector <double> dvals; 5 vector<double>::iterator iter; 6 int pos; 7 row.erase(row.begin(), row.end()); 8 ifstream fin("path_to_the_source_file"); 9 while(getline(fin, row)) 10 { 11 cout << "Input: " << row << "\n"; 12 while((pos = row.find(";",0)) != -1) 13 { 14 row.replace(pos, 1, " "); 15 } 16 istringstream is(row); 17 is >> rowhead; 18 while(!is.eof()) 19 { 20 is >> dval; 21 if(!is.eof()) dvals.push_back(dval); 22 } 23 cout << "Output: " << rowhead << ";"; 24 for(iter = dvals.begin(); iter < dvals.end(); iter++) 25 cout << *iter << ((iter == dvals.end() - 1) ? "\n" : ";"); 26 row.erase(row.begin(), row.end()); 27 dvals.clear(); 28 } |
try to use file.eof() to signify eof file, don't use the output of getline.
btw. I'm horible with c++ stl, so i'm no help here. sorry |
All times are GMT -5. The time now is 04:38 AM. |