Hello all,
I need to read in from a csv file and store in an integer array, after read in the line and split the line with boost::split, I got a vector<string> LineItems. I can convert it to integer array by:
1 2 3
for (int i=0; i<=10; i++){
WorkArr[i]=stoi(LineItems[i]);
}
(I know the size and format of the csv therefore I can use an array to store.)
However, I would like to use transform to perform this task:
@CFLam
If you are absolutely certain that:
(a) your file contains ONLY integer (or only double) data;
(b) there are no empty cells;
then you could circumvent the string conversions completely and read straight into a numerical array.
(If you can't meet those conditions then it is safer to read into strings and convert where possible.)
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
usingnamespace std;
//======================================================================
/*
Reads a SINGLE LINE containing ...
... an UNKNOWN NUMBER of ...
... SINGLE PUNCTUATION-SEPARATED values ...
... into a vector<T> of CONSISTENT NUMERICAL type
*/
template <typename T> istream &operator >> ( istream &in, vector<T> &V )
{
string line;
T item;
char separator;
V.clear(); // In case V had anything in on entry
getline( in, line ); // If you don't know how many values per line, you must ISOLATE ONE LINE
stringstream ss( line ); // Create an internal stream from this line only
while ( ss >> item ) // Whilst the next item ON THIS LINE is NUMERICAL
{
V.push_back( item ); // ... put it in the vector ...
ss >> separator; // ... and clear ANY following non-white-space character (probably none at end of line)
}
return in; // This will allow input to continue on the main stream
}
//======================================================================
template <typename T> vector< vector<T> > readCSV( string filename )
{
vector< vector<T> > matrix;
vector<T> row;
ifstream in( filename ); if ( !in ) { cout << "Can't open " << filename << '\n'; return matrix; }
while ( in >> row ) if ( !row.empty() ) matrix.push_back( row );
return matrix;
}
//======================================================================
int main()
{
vector< vector<int> > matrix = readCSV<int>( "input.csv" );
cout << "File read:\n";
for ( auto row : matrix )
{
for ( auto e : row ) cout << e << " ";
cout << '\n';
}
}
//======================================================================
@lastchance, the csv contain empty cell and mix string with integer, but I know exactly which cell contain string and which for integer, therefore I need to convert them explictly ~_~.