owlps/owlps-positioning/src/csvfilereader.hh

70 lines
1.4 KiB
C++

#ifndef _OWLPS_POSITIONING_CSVFILEREADER_HH_
#define _OWLPS_POSITIONING_CSVFILEREADER_HH_
#include "textfilereader.hh"
#include <boost/tokenizer.hpp>
#include <boost/lexical_cast.hpp>
/// Reads a CSV file, line by line, field by field
class CSVFileReader: public TextFileReader
{
protected:
const char separator ;
std::string current_line ;
boost::tokenizer<boost::escaped_list_separator<char> > *current_token ;
boost::tokenizer<boost::escaped_list_separator<char> >::const_iterator
token_iterator ;
unsigned int current_field_nb ;
void print_error_cast(void) ;
public:
CSVFileReader(const std::string &filename,
const char _separator = ';'):
TextFileReader(filename), separator(_separator),
current_token(NULL) {}
virtual ~CSVFileReader(void) ;
/** @name Operations */
//@{
/// Load the first next non-blank line
bool next_line(void) ;
/// Read the next field of the current line
template<class T> bool read_field(T &field) ;
//@}
} ;
/* *** Operations *** */
template<class T>
inline bool CSVFileReader::read_field(T &field)
{
if (token_iterator == current_token->end())
return false ;
++current_field_nb ;
try
{
field = boost::lexical_cast<T>(*token_iterator) ;
}
catch (boost::bad_lexical_cast &e)
{
print_error_cast() ;
return false ;
}
++token_iterator ;
return true ;
}
#endif // _OWLPS_POSITIONING_CSVFILEREADER_HH_