Chinaunix首页 | 论坛 | 博客
  • 博客访问: 397085
  • 博文数量: 466
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 10
  • 用 户 组: 普通用户
  • 注册时间: 2015-03-16 13:59
文章分类

全部博文(466)

文章存档

2015年(466)

我的朋友

分类: C/C++

2015-03-16 14:55:32

原文地址:CSV文件解析 C++ (转) 作者:linux_wuliqiang


http://www.cnblogs.com/huoguofeng/archive/2010/11/24/1887087.html


点击(此处)折叠或打开

  1. 其一:
  2. /* Copyright (C) 1999 Lucent Technologies */
  3. /* Excerpted from 'The Practice of Programming' */
  4. /* by Brian W. Kernighan and Rob Pike */

  5. #include <iostream>
  6. #include <algorithm>
  7. #include <string>
  8. #include <vector>

  9. using namespace std;

  10. class Csv
  11. { // read and parse comma-separated values
  12.     // sample input: "LU",86.25,"11/4/1998","2:19PM",+4.0625

  13. public:
  14.     Csv(istream& fin = cin, string sep = ",") :
  15.       fin(fin), fieldsep(sep) {}

  16.       int getline(string&);
  17.       string getfield(int n);
  18.       int getnfield() const { return nfield; }

  19. private:
  20.     istream& fin; // input file pointer
  21.     string line; // input line
  22.     vector<string> field; // field strings
  23.     int nfield; // number of fields
  24.     string fieldsep; // separator characters

  25.     int split();
  26.     int endofline(char);
  27.     int advplain(const string& line, string& fld, int);
  28.     int advquoted(const string& line, string& fld, int);
  29. };

  30. // endofline: check for and consume \r, \n, \r\n, or EOF
  31. int Csv::endofline(char c)
  32. {
  33.     int eol;

  34.     eol = (c=='\r' || c=='\n');
  35.     if (c == '\r')
  36.     {
  37.         fin.get(c);
  38.         if (!fin.eof() && c != '\n')
  39.             fin.putback(c); // read too far
  40.     }
  41.     return eol;
  42. }

  43. // getline: get one line, grow as needed
  44. int Csv::getline(string& str)
  45. {
  46.     char c;

  47.     for (line = ""; fin.get(c) && !endofline(c); )
  48.         line += c;
  49.     split();
  50.     str = line;
  51.     return !fin.eof();
  52. }

  53. // split: split line into fields
  54. int Csv::split()
  55. {
  56.     string fld;
  57.     int i, j;

  58.     nfield = 0;
  59.     if (line.length() == 0)
  60.         return 0;
  61.     i = 0;

  62.     do {
  63.         if (i < line.length() && line[i] == '"')
  64.             j = advquoted(line, fld, ++i); // skip quote
  65.         else
  66.             j = advplain(line, fld, i);
  67.         if (nfield >= field.size())
  68.             field.push_back(fld);
  69.         else
  70.             field[nfield] = fld;
  71.         nfield++;
  72.         i = j + 1;
  73.     } while (j < line.length());

  74.     return nfield;
  75. }

  76. // advquoted: quoted field; return index of next separator
  77. int Csv::advquoted(const string& s, string& fld, int i)
  78. {
  79.     int j;

  80.     fld = "";
  81.     for (j = i; j < s.length(); j++)
  82.     {
  83.         if (s[j] == '"' && s[++j] != '"')
  84.         {
  85.             int k = s.find_first_of(fieldsep, j);
  86.             if (k > s.length()) // no separator found
  87.                 k = s.length();
  88.             for (k -= j; k-- > 0; )
  89.                 fld += s[j++];
  90.             break;
  91.         }
  92.         fld += s[j];
  93.     }
  94.     return j;
  95. }

  96. // advplain: unquoted field; return index of next separator
  97. int Csv::advplain(const string& s, string& fld, int i)
  98. {
  99.     int j;

  100.     j = s.find_first_of(fieldsep, i); // look for separator
  101.     if (j > s.length()) // none found
  102.         j = s.length();
  103.     fld = string(s, i, j-i);
  104.     return j;
  105. }


  106. // getfield: return n-th field
  107. string Csv::getfield(int n)
  108. {
  109.     if (n < 0 || n >= nfield)
  110.         return "";
  111.     else
  112.         return field[n];
  113. }

  114. // Csvtest main: test Csv class
  115. int main(void)
  116. {
  117.     string line;
  118.     Csv csv;

  119.     while (csv.getline(line) != 0)
  120.     {
  121.         cout << "line = `" << line <<"'\n";
  122.         for (int i = 0; i < csv.getnfield(); i++)
  123.             cout << "field[" << i << "] = `"
  124.             << csv.getfield(i) << "'\n";
  125.     }
  126.     return 0;
  127. }




  128. 其二:
  129. 来源于:
  130. 头文件:
  131. #ifndef __CSVPARSE_H_2001_06_07__
  132. #define __CSVPARSE_H_2001_06_07__

  133. /*
  134. Copyright (c) 2001, Mayukh Bose
  135. All rights reserved.

  136. Redistribution and use in source and binary forms, with or without
  137. modification, are permitted provided that the following conditions are
  138. met:

  139. * Redistributions of source code must retain the above copyright notice,
  140. this list of conditions and the following disclaimer.

  141. * Redistributions in binary form must reproduce the above copyright
  142. notice, this list of conditions and the following disclaimer in the
  143. documentation and/or other materials provided with the distribution.

  144. * Neither the name of Mayukh Bose nor the names of other
  145. contributors may be used to endorse or promote products derived from
  146. this software without specific prior written permission.

  147. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  148. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  149. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  150. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  151. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  152. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  153. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  154. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  155. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  156. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  157. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  158. */

  159. #include
  160. using namespace std;

  161. class CSVParser {
  162.  private:
  163.   string m_sData;
  164.   string::size_type m_nPos;
  165.   void SkipSpaces(void);
  166.  public:
  167.   CSVParser();
  168.   const CSVParser & operator << (const string &sIn);
  169.   const CSVParser & operator << (const char *sIn);
  170.   CSVParser & operator >> (int &nOut);
  171.   CSVParser & operator >> (double &nOut);
  172.   CSVParser & operator >> (string &sOut);
  173. };

  174. #endif


  175. cpp
  176. /*
  177. Copyright (c) 2001, Mayukh Bose
  178. All rights reserved.

  179. Redistribution and use in source and binary forms, with or without
  180. modification, are permitted provided that the following conditions are
  181. met:

  182. * Redistributions of source code must retain the above copyright notice,
  183. this list of conditions and the following disclaimer.

  184. * Redistributions in binary form must reproduce the above copyright
  185. notice, this list of conditions and the following disclaimer in the
  186. documentation and/or other materials provided with the distribution.

  187. * Neither the name of Mayukh Bose nor the names of other
  188. contributors may be used to endorse or promote products derived from
  189. this software without specific prior written permission.

  190. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  191. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  192. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  193. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  194. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  195. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  196. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  197. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  198. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  199. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  200. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  201. */

  202. #include
  203. #include
  204. #include "csvparser.h"
  205. using namespace std;


  206. CSVParser::CSVParser()
  207. {
  208.   m_sData = "";
  209.   m_nPos = 0;
  210. }

  211. void CSVParser::SkipSpaces(void)
  212. {
  213.   while (m_nPos < m_sData.length() && m_sData[m_nPos] == ' ')
  214.     m_nPos++;
  215. }

  216. const CSVParser & CSVParser::operator <<(const string & sIn)
  217. {
  218.   this->m_sData = sIn;
  219.   this->m_nPos = 0;
  220.   return *this;
  221. }

  222. const CSVParser & CSVParser::operator <<(const char *sIn)
  223. {
  224.   this->m_sData = sIn;
  225.   this->m_nPos = 0;
  226.   return *this;
  227. }

  228. CSVParser & CSVParser::operator >>(int & nOut)
  229. {
  230.   string sTmp = "";
  231.   SkipSpaces();
  232.   while (m_nPos < m_sData.length() && m_sData[m_nPos] != ',')
  233.     sTmp += m_sData[m_nPos++];

  234.   m_nPos++; // skip past comma
  235.   nOut = atoi(sTmp.c_str());
  236.   return *this;
  237. }

  238. CSVParser & CSVParser::operator >>(double & nOut)
  239. {
  240.   string sTmp = "";
  241.   SkipSpaces();
  242.   while (m_nPos < m_sData.length() && m_sData[m_nPos] != ',')
  243.     sTmp += m_sData[m_nPos++];

  244.   m_nPos++; // skip past comma
  245.   nOut = atof(sTmp.c_str());
  246.   return *this;
  247. }

  248. CSVParser & CSVParser::operator >>(string & sOut)
  249. {
  250.   bool bQuotes = false;
  251.   sOut = "";
  252.   SkipSpaces();

  253.   // Jump past first " if necessary
  254.   if (m_nPos < m_sData.length() && m_sData[m_nPos] == '"') {
  255.     bQuotes = true;
  256.     m_nPos++;
  257.   }
  258.   
  259.   while (m_nPos < m_sData.length()) {
  260.     if (!bQuotes && m_sData[m_nPos] == ',')
  261.       break;
  262.     if (bQuotes && m_sData[m_nPos] == '"') {
  263.       if (m_nPos + 1 >= m_sData.length() - 1)
  264.         break;
  265.       if (m_sData[m_nPos+1] == ',')
  266.         break;
  267.     }
  268.     sOut += m_sData[m_nPos++];
  269.   }

  270.   // Jump past last " if necessary
  271.   if (bQuotes && m_nPos < m_sData.length() && m_sData[m_nPos] == '"')
  272.     m_nPos++;

  273.   // Jump past , if necessary
  274.   if (m_nPos < m_sData.length() && m_sData[m_nPos] == ',')
  275.     m_nPos++;

  276.   return *this;
  277. }

demo : csvclass.zip   

Demo2,已经验证: CsvParse_CppVersion.zip   
阅读(1478) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~