Main Page | Namespace List | Class Hierarchy | Alphabetical List | Class List | File List | Namespace Members | Class Members | File Members

csvparser.h

Go to the documentation of this file.
00001 #ifndef _CSVPARSE_H
00002 #define _CSVPARSE_H
00003 
00006 //BOOST
00007 #include <boost/lexical_cast.hpp>
00008 
00009 #include "stdlib.h"
00010 #include <iostream>
00011 #include <string>
00012 
00013 namespace CSVConst{
00014 
00015   const std::string separator = ",";
00016 };
00017 
00018 class CSVParser {
00019 
00020 public:
00021 
00022   CSVParser(const std::string& sIn);
00023 
00024   ~CSVParser(){}
00025 
00026   typedef std::string::size_type size_type;
00027   
00028 
00029   template <class TYPE>  
00030   CSVParser & operator >> (TYPE& out);
00031 
00032 
00033  private:
00034 
00035   std::string m_sData;
00036   std::string::size_type m_nPos;
00037   void SkipSpaces();
00038   std::string next();
00039 
00040 };
00041 
00042 inline CSVParser::CSVParser(const std::string& sIn):
00043 m_sData(sIn),
00044 m_nPos(0)
00045 {
00046  // constructer 
00047 }
00048 
00049 template <class TYPE>
00050 inline CSVParser& CSVParser::operator >> (TYPE& out)  {
00051 
00052   // stream 
00053   std::string str = next(); 
00054   try{
00055     out = boost::lexical_cast<TYPE>(str);
00056   }
00057   catch(boost::bad_lexical_cast& e){
00058       std::cerr << " ERROR " << e.what()   << std::endl; 
00059       abort();
00060   }
00061   return *this;
00062 }
00063 
00064 template <>
00065 inline CSVParser& CSVParser::operator >> (std::string& out)  {
00066 
00067   // specializition for string - take up to first white space
00068   std::string tmp = next(); 
00069   size_type pos = 0;
00070   while (pos < tmp.size() && tmp[pos] != ' ') ++pos;
00071   out = tmp.substr(0,pos); 
00072   return *this;    
00073 }
00074 
00075 inline void CSVParser::SkipSpaces(){
00076   // skip leading whitespace
00077   while (m_nPos < m_sData.size() && m_sData[m_nPos] == ' ')
00078     ++m_nPos;
00079 }
00080 
00081 inline std::string CSVParser::next(){
00082   // next token 
00083   SkipSpaces();
00084   size_type pos = m_sData.find(CSVConst::separator,m_nPos); 
00085   std::string tStr = m_sData.substr(m_nPos,pos-m_nPos); 
00086   m_nPos = pos+1;
00087 
00088   return tStr;  
00089 }
00090 
00091 #endif
00092 

Generated on Fri Jul 8 16:38:52 2005 for Salamander by  doxygen 1.4.1