Trying to sum all rows and cols (valid doubles only) of the following file by making a vec of vecs out of it and then using an istringstream to validate doubles:
18,459,45A,AG7,490,486
4A 2,65,-87,432,-43,0
67,3G,5T,TEA,COFFEE,5
3.14,2.71,654,2334,66,8
a,b,c,d,18,f
cafecafe,4,-4,3,2,6
using the code:
#include "csv_parser.hpp"
using namespace std;
int main(int argc, char const *argv[]){
parse_csv("example.csv");
}
void parse_csv(string fname){
ifstream file(fname);
vector<string> lines;
vector<vector<string>> data;
string line;
while(getline(file, line)){
data.push_back(vector<string>());
stringstream ss(line);
string val;
while (getline(ss, val, ',')){
data.back().push_back(val);
}
}
// print data
for(auto row : data){
for(auto col : row){
cout << col << " ";
}
cout << endl;
}
for(unsigned int r = 0; r < data.size(); r++){
double sum = 0;
for(int c = 0; c < data.front().size(); c++){
std::istringstream ss(data[r][c]);
cout << "curr data " << ss.str() << endl;
double d;
ss >> d;
if(ss.fail() || !ss.eof())
std::cout << "Failed to parse " << data[r][c] << endl;
else
sum += d;
}
std::cout << "Row " << r << " sum: " << sum << endl;
}
for(int c = 0; c < data.size(); c++){
double sum = 0;
for(int r = 0; r < data.front().size(); r++){
std::stringstream ss(data[r][c]);
double d;
std::string postfix;
ss >> d;
if(!ss.fail() && !(ss >> postfix))
sum += d;
else
ss.clear();
}
cout << "Column " << c << " sum: " << sum << endl;
}
}
consider only the first for loop (because the two loops will be almost the same) ss always fails on the first 18, and swapping it with the 459 next to it also fails the 459, but then the 18 doesn’t fail.
I tried swapping entries as I said, printing the state with .good() (it becomes bad after trying to flush ss into the double) and adding another item before it, that makes the new item fail but 18 to not fail.
user36474 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.