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
|
#include <iostream>
#include <string>
#include <cctype>
#include <fstream>
#include <vector>
#include <iomanip>
std::string trim( std::string str ) // remove leading and trailing ws
{
// knock off trailing spaces
while( !str.empty() && std::isspace( str.back() ) ) str.pop_back() ;
// get the position of the first non-ws character
std::size_t pos = 0 ;
while( pos < str.size() && std::isspace( str[pos] ) ) ++pos ;
return str.substr(pos) ; // return substring from the first non-ws character
}
std::string last_fld_of( const std::string& csv )
{
const auto pos = csv.rfind( ',' ) ; // position of the last comma
if( pos != std::string::npos ) // found last comma
return trim( csv.substr(pos+1) ) ; // return the fld after the comma
else return trim(csv) ; // did not find a comma, return the entire string
}
std::vector<std::string> get_last_flds( std::istream& stm )
{
std::vector<std::string> result ;
std::string line ;
while( std::getline( stm, line ) ) // for each line in the file
result.push_back( last_fld_of(line) ) ;// move the last fld to vector
return result ;
}
int main()
{
const std::string file_name = "my_csv.csv" ;
{
// create a test file
std::ofstream(file_name) << "5.1,3.5,1.4,0.2,no\n" // 1
"4.9,3.0,1.4,0.2, yes \n" // 2
"4.7,3.2,1.3,,no\n" // 3
"\n" // 4
"YES\n" // 5
"4.6,3.1,1.5,0.2,yes \n" // 6
"5.0,3.6,1.4,0.2, no\n" // 7
"5.4,3.9,1.7,0.4,yes\n" ; // 8
}
std::ifstream file(file_name) ; // open the file for input
const std::vector<std::string> last_flds = get_last_flds(file) ;
for( std::size_t i = 0 ; i < last_flds.size() ; ++i )
std::cout << "last fld of line #" << i+1 << ' ' << std::quoted( last_flds[i] ) << '\n' ;
}
|