1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
|
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
std::string& trim_right(
std::string& s,
const std::string& delimiters = " \f\n\r\t\v" )
{
return s.erase( s.find_last_not_of( delimiters ) + 1 );
}
std::string& trim_left(
std::string& s,
const std::string& delimiters = " \f\n\r\t\v" )
{
return s.erase( 0, s.find_first_not_of( delimiters ) );
}
std::string& trim(
std::string& s,
const std::string& delimiters = " \f\n\r\t\v" )
{
return trim_left( trim_right( s, delimiters ), delimiters );
}
std::vector <std::vector <std::string> >
read_csv( const std::string& filename, char delimiter = ',' )
{
std::vector <std::vector <std::string> > result;
std::ifstream f( filename );
if (!f) throw std::runtime_error( "read_csv(): Failure to open file " + filename );
std::string s;
while (getline( f, s ))
{
if (trim( s ).empty()) continue;
std::vector <std::string> row;
std::istringstream ss( s );
while (getline( ss, s, delimiter ))
row.emplace_back( trim( s ) );
result.emplace_back( row );
}
return result;
}
#include <algorithm>
#include <iostream>
int main( int argc, char** argv )
{
if (argc != 2)
{
std::cerr << "usage:\n " << argv[0] << " CSVFILE\n\n"
"Reads a comma-separated CSV file containing NO quotes.\n";
return 1;
}
try
{
// Read the CSV file
auto table = read_csv( argv[1] );
// Print number of records
std::cout << table.size() << " records\n";
// Print max number of fields per record
std::cout << std::max_element( table.begin(), table.end(),
[]( const std::vector <std::string> & a, const std::vector <std::string> & b )
{
return a.size() < b.size();
}
)->size() << " fields per record\n";
// Print the first 5 records (or as many as available)
auto N = std::min( (std::size_t)5, table.size() );
const char* commas[] = { "", ", " };
std::cout << "First " << N << " records:\n";
for (std::size_t n = 0; n < N; n++)
{
bool b = false;
std::cout << " " << n << " : ";
for (auto s : table[n])
std::cout << commas[b++] << s;
std::cout << "\n";
}
// Print the last 5 records
std::cout << "Last " << N << " records:\n";
for (std::size_t n = 0; n < N; n++)
{
bool b = false;
std::cout << " " << (table.size() - N + n) << " : ";
for (auto s : table[table.size() - N + n])
std::cout << commas[b++] << s;
std::cout << "\n";
}
}
catch (const std::exception& e)
{
std::cerr << e.what() << "\n";
return 1;
}
}
|