c++11 - Read csv column names in C++ -
i new object oriented programming. firstly, trying read following data structure csv file , parse through first line (header) , push strings vector. secondly, read customer information on first row (usa) , extract name , integer value(14400000). far, existing code read columns. however, there spaces within of strings , trim them.
+------------------------------------------------------+ |,abb llc,phil manu ,products north america inc.,mapn, | +------------------------------------------------------+ | usa-14400000,,,, | | quantity,14155572,14435598,14298563,14311206 | | index,us-gc,eu-ht,as-ir,us-pt | | period(weeks),3,3,3,3 | | cost,6278,5341,7394,7069 | +------------------------------------------------------+
here code.
#include <iostream> #include <fstream> #include <sstream> using namespace std; void readtest() { string filename = doe->scenariodir( ) + "/test.csv"; // read data ifstream fin( filename ); if ( fin == null ) { cout << "missing test.csv file." << endl; exit(1); } cout << "\nreading file " << filename << endl; vector<string> supplierslist; string str, suppliername; getline( fin, str ); stringstream linestr( str ); getline( linestr, suppliername,',' ); while ( linestr.good() ) { getline( linestr, suppliername, ',' ); supplierslist.push_back(suppliername); } std::cout << supplierslist[0] << ' '; }
and output : abb llc
any appreciated!
your code works designed. following line prints first element:
std::cout << supplierslist[0] << ' ';
if you'd change follows:
for (auto &x: supplierslist) std::cout << x << ' ';
you'd obtain full list:
abb llc phil manu products north america inc. mapn
by way:
- you should replace
if(fin==null)
if(!fin)
- and should loop on read operation:
while(getline( linestr, suppliername, ',' ))
instead ofwhile(linestr.good())
followed read you'd try process if it'd fail.
edit: how rid of spaces
if want rid of spaces, use copy_if()
back_inserter()
follows:
... string str, field; ... getline( linestr, field,',' ); while ( getline( linestr, field, ',' ) ) { string suppliername; copy_if(field.begin(), field.end(), back_inserter<string>(suppliername),[](char a){return !isspace(a);}); supplierslist.push_back(suppliername); } ...
this give you:
abbllc philmanu productsnorthamericainc. mapn
Comments
Post a Comment