两个 CSV 解析类

本文涉及的产品
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
简介:
其一:
ExpandedBlockStart.gif /* Copyright (C) 1999 Lucent Technologies */
ExpandedBlockStart.gif /* Excerpted from 'The Practice of Programming' */
ExpandedBlockStart.gif /* by Brian W. Kernighan and Rob Pike */
None.gif
None.gif#include <iostream>
None.gif#include <algorithm>
None.gif#include < string>
None.gif#include <vector>
None.gif
None.gif using  namespace std;
None.gif
None.gif class Csv
ExpandedBlockStart.gif {    // read and parse comma-separated values
InBlock.gif    
// sample input: "LU",86.25,"11/4/1998","2:19PM",+4.0625
InBlock.gif

InBlock.gifpublic:
InBlock.gif    Csv(istream& fin = cin, string sep = ",") : 
ExpandedSubBlockStart.gif      fin(fin), fieldsep(sep) {}
InBlock.gif
InBlock.gif      int getline(string&);
InBlock.gif      string getfield(int n);
ExpandedSubBlockStart.gif      int getnfield() const return nfield; }
InBlock.gif
InBlock.gifprivate:
InBlock.gif    istream& fin;            // input file pointer
InBlock.gif
    string line;            // input line
InBlock.gif
    vector<string> field;    // field strings
InBlock.gif
    int nfield;                // number of fields
InBlock.gif
    string fieldsep;        // separator characters
InBlock.gif

InBlock.gif    int split();
InBlock.gif    int endofline(char);
InBlock.gif    int advplain(const string& line, string& fld, int);
InBlock.gif    int advquoted(const string& line, string& fld, int);
ExpandedBlockEnd.gif}
;
None.gif
None.gif //  endofline: check for and consume \r, \n, \r\n, or EOF
None.gif
int Csv::endofline( char c)
ExpandedBlockStart.gif {
InBlock.gif    int eol;
InBlock.gif
InBlock.gif    eol = (c=='\r' || c=='\n');
InBlock.gif    if (c == '\r')
ExpandedSubBlockStart.gif    {
InBlock.gif        fin.get(c);
InBlock.gif        if (!fin.eof() && c != '\n')
InBlock.gif            fin.putback(c);    // read too far
ExpandedSubBlockEnd.gif
    }

InBlock.gif    return eol;
ExpandedBlockEnd.gif}

None.gif
None.gif //  getline: get one line, grow as needed
None.gif
int Csv::getline( string& str)
ExpandedBlockStart.gif {    
InBlock.gif    char c;
InBlock.gif
InBlock.gif    for (line = ""; fin.get(c) && !endofline(c); )
InBlock.gif        line += c;
InBlock.gif    split();
InBlock.gif    str = line;
InBlock.gif    return !fin.eof();
ExpandedBlockEnd.gif}

None.gif
None.gif //  split: split line into fields
None.gif
int Csv::split()
ExpandedBlockStart.gif {
InBlock.gif    string fld;
InBlock.gif    int i, j;
InBlock.gif
InBlock.gif    nfield = 0;
InBlock.gif    if (line.length() == 0)
InBlock.gif        return 0;
InBlock.gif    i = 0;
InBlock.gif
ExpandedSubBlockStart.gif    do {
InBlock.gif        if (i < line.length() && line[i] == '"')
InBlock.gif            j = advquoted(line, fld, ++i);    // skip quote
InBlock.gif
        else
InBlock.gif            j = advplain(line, fld, i);
InBlock.gif        if (nfield >= field.size())
InBlock.gif            field.push_back(fld);
InBlock.gif        else
InBlock.gif            field[nfield] = fld;
InBlock.gif        nfield++;
InBlock.gif        i = j + 1;
ExpandedSubBlockEnd.gif    }
 while (j < line.length());
InBlock.gif
InBlock.gif    return nfield;
ExpandedBlockEnd.gif}

None.gif
None.gif //  advquoted: quoted field; return index of next separator
None.gif
int Csv::advquoted( const  string& s,  string& fld,  int i)
ExpandedBlockStart.gif {
InBlock.gif    int j;
InBlock.gif
InBlock.gif    fld = "";
InBlock.gif    for (j = i; j < s.length(); j++)
ExpandedSubBlockStart.gif    {
InBlock.gif        if (s[j] == '"' && s[++j] != '"')
ExpandedSubBlockStart.gif        {
InBlock.gif            int k = s.find_first_of(fieldsep, j);
InBlock.gif            if (k > s.length())    // no separator found
InBlock.gif
                k = s.length();
InBlock.gif            for (k -= j; k-- > 0; )
InBlock.gif                fld += s[j++];
InBlock.gif            break;
ExpandedSubBlockEnd.gif        }

InBlock.gif        fld += s[j];
ExpandedSubBlockEnd.gif    }

InBlock.gif    return j;
ExpandedBlockEnd.gif}

None.gif
None.gif //  advplain: unquoted field; return index of next separator
None.gif
int Csv::advplain( const  string& s,  string& fld,  int i)
ExpandedBlockStart.gif {
InBlock.gif    int j;
InBlock.gif
InBlock.gif    j = s.find_first_of(fieldsep, i); // look for separator
InBlock.gif
    if (j > s.length())               // none found
InBlock.gif
        j = s.length();
InBlock.gif    fld = string(s, i, j-i);
InBlock.gif    return j;
ExpandedBlockEnd.gif}

None.gif
None.gif
None.gif //  getfield: return n-th field
None.gif
string Csv::getfield( int n)
ExpandedBlockStart.gif {
InBlock.gif    if (n < 0 || n >= nfield)
InBlock.gif        return "";
InBlock.gif    else
InBlock.gif        return field[n];
ExpandedBlockEnd.gif}

None.gif
None.gif //  Csvtest main: test Csv class
None.gif
int main( void)
ExpandedBlockStart.gif {
InBlock.gif    string line;
InBlock.gif    Csv csv;
InBlock.gif
InBlock.gif    while (csv.getline(line) != 0)
ExpandedSubBlockStart.gif    {
InBlock.gif        cout << "line = `" << line <<"'\n";
InBlock.gif        for (int i = 0; i < csv.getnfield(); i++)
InBlock.gif            cout << "field[" << i << "] = `"
InBlock.gif            << csv.getfield(i) << "'\n";
ExpandedSubBlockEnd.gif    }

InBlock.gif    return 0;
ExpandedBlockEnd.gif}

None.gif
None.gif


其二:
来源于: http://www.mayukhbose.com/freebies/c-code.php
头文件:
None.gif#ifndef __CSVPARSE_H_2001_06_07__
None.gif #define __CSVPARSE_H_2001_06_07__
None.gif
ExpandedBlockStart.gif /*
InBlock.gifCopyright (c) 2001, Mayukh Bose
InBlock.gifAll rights reserved.
InBlock.gif
InBlock.gifRedistribution and use in source and binary forms, with or without
InBlock.gifmodification, are permitted provided that the following conditions are
InBlock.gifmet:
InBlock.gif
InBlock.gif* Redistributions of source code must retain the above copyright notice,
InBlock.gifthis list of conditions and the following disclaimer.  
InBlock.gif
InBlock.gif* Redistributions in binary form must reproduce the above copyright
InBlock.gifnotice, this list of conditions and the following disclaimer in the
InBlock.gifdocumentation and/or other materials provided with the distribution.
InBlock.gif
InBlock.gif* Neither the name of Mayukh Bose nor the names of other
InBlock.gifcontributors may be used to endorse or promote products derived from
InBlock.gifthis software without specific prior written permission.
InBlock.gif
InBlock.gifTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
InBlock.gif"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
InBlock.gifLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
InBlock.gifA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
InBlock.gifOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
InBlock.gifSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
InBlock.gifLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
InBlock.gifDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
InBlock.gifTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
InBlock.gif(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
InBlock.gifOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
ExpandedBlockEnd.gif
*/

None.gif
None.gif#include < string>
None.gif using  namespace std;
None.gif
ExpandedBlockStart.gif class CSVParser  {
InBlock.gif private:
InBlock.gif  string m_sData;
InBlock.gif  string::size_type m_nPos;
InBlock.gif  void SkipSpaces(void);
InBlock.gif public:
InBlock.gif  CSVParser();
InBlock.gif  const CSVParser & operator << (const string &sIn);
InBlock.gif  const CSVParser & operator << (const char *sIn);
InBlock.gif  CSVParser & operator >> (int &nOut);
InBlock.gif  CSVParser & operator >> (double &nOut);
InBlock.gif  CSVParser & operator >> (string &sOut);
ExpandedBlockEnd.gif}
;
None.gif
None.gif #endif
None.gif

cpp
ExpandedBlockStart.gif /*
InBlock.gifCopyright (c) 2001, Mayukh Bose
InBlock.gifAll rights reserved.
InBlock.gif
InBlock.gifRedistribution and use in source and binary forms, with or without
InBlock.gifmodification, are permitted provided that the following conditions are
InBlock.gifmet:
InBlock.gif
InBlock.gif* Redistributions of source code must retain the above copyright notice,
InBlock.gifthis list of conditions and the following disclaimer.  
InBlock.gif
InBlock.gif* Redistributions in binary form must reproduce the above copyright
InBlock.gifnotice, this list of conditions and the following disclaimer in the
InBlock.gifdocumentation and/or other materials provided with the distribution.
InBlock.gif
InBlock.gif* Neither the name of Mayukh Bose nor the names of other
InBlock.gifcontributors may be used to endorse or promote products derived from
InBlock.gifthis software without specific prior written permission.
InBlock.gif
InBlock.gifTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
InBlock.gif"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
InBlock.gifLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
InBlock.gifA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
InBlock.gifOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
InBlock.gifSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
InBlock.gifLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
InBlock.gifDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
InBlock.gifTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
InBlock.gif(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
InBlock.gifOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
ExpandedBlockEnd.gif
*/

None.gif
None.gif#include <iostream>
None.gif#include <cstdlib>
None.gif#include "csvparser.h"
None.gif using  namespace std;
None.gif
None.gif
None.gifCSVParser::CSVParser()
ExpandedBlockStart.gif {
InBlock.gif  m_sData = "";
InBlock.gif  m_nPos = 0;
ExpandedBlockEnd.gif}

None.gif
None.gif void CSVParser::SkipSpaces( void)
ExpandedBlockStart.gif {
InBlock.gif  while (m_nPos < m_sData.length() && m_sData[m_nPos] == ' ')
InBlock.gif    m_nPos++;
ExpandedBlockEnd.gif}

None.gif
None.gif const CSVParser & CSVParser:: operator <<( const  string & sIn)
ExpandedBlockStart.gif {
InBlock.gif  this->m_sData = sIn;
InBlock.gif  this->m_nPos = 0;
InBlock.gif  return *this;
ExpandedBlockEnd.gif}

None.gif
None.gif const CSVParser & CSVParser:: operator <<( const  char *sIn)
ExpandedBlockStart.gif {
InBlock.gif  this->m_sData = sIn;
InBlock.gif  this->m_nPos = 0;
InBlock.gif  return *this;
ExpandedBlockEnd.gif}

None.gif
None.gifCSVParser & CSVParser:: operator >>( int & nOut)
ExpandedBlockStart.gif {
InBlock.gif  string sTmp = "";
InBlock.gif  SkipSpaces();
InBlock.gif  while (m_nPos < m_sData.length() && m_sData[m_nPos] != ',')
InBlock.gif    sTmp += m_sData[m_nPos++];
InBlock.gif
InBlock.gif  m_nPos++; // skip past comma
InBlock.gif
  nOut = atoi(sTmp.c_str());
InBlock.gif  return *this;
ExpandedBlockEnd.gif}

None.gif
None.gifCSVParser & CSVParser:: operator >>( double & nOut)
ExpandedBlockStart.gif {
InBlock.gif  string sTmp = "";
InBlock.gif  SkipSpaces();
InBlock.gif  while (m_nPos < m_sData.length() && m_sData[m_nPos] != ',')
InBlock.gif    sTmp += m_sData[m_nPos++];
InBlock.gif
InBlock.gif  m_nPos++; // skip past comma
InBlock.gif
  nOut = atof(sTmp.c_str());
InBlock.gif  return *this;
ExpandedBlockEnd.gif}

None.gif
None.gifCSVParser & CSVParser:: operator >>( string & sOut)
ExpandedBlockStart.gif {
InBlock.gif  bool bQuotes = false;
InBlock.gif  sOut = "";
InBlock.gif  SkipSpaces();
InBlock.gif
InBlock.gif  // Jump past first " if necessary
ExpandedSubBlockStart.gif
  if (m_nPos < m_sData.length() && m_sData[m_nPos] == '"') {
InBlock.gif    bQuotes = true;
InBlock.gif    m_nPos++; 
ExpandedSubBlockEnd.gif  }

InBlock.gif  
ExpandedSubBlockStart.gif  while (m_nPos < m_sData.length()) {
InBlock.gif    if (!bQuotes && m_sData[m_nPos] == ',')
InBlock.gif      break;
ExpandedSubBlockStart.gif    if (bQuotes && m_sData[m_nPos] == '"') {
InBlock.gif      if (m_nPos + 1 >= m_sData.length() - 1)
InBlock.gif        break;
InBlock.gif      if (m_sData[m_nPos+1] == ',')
InBlock.gif        break;
ExpandedSubBlockEnd.gif    }

InBlock.gif    sOut += m_sData[m_nPos++];
ExpandedSubBlockEnd.gif  }

InBlock.gif
InBlock.gif  // Jump past last " if necessary
InBlock.gif
  if (bQuotes && m_nPos < m_sData.length() && m_sData[m_nPos] == '"')
InBlock.gif    m_nPos++; 
InBlock.gif
InBlock.gif  // Jump past , if necessary
InBlock.gif
  if (m_nPos < m_sData.length() && m_sData[m_nPos] == ',')
InBlock.gif    m_nPos++; 
InBlock.gif
InBlock.gif  return *this;
ExpandedBlockEnd.gif}
目录
相关文章
|
26天前
|
存储 C++ 容器
C++入门指南:string类文档详细解析(非常经典,建议收藏)
C++入门指南:string类文档详细解析(非常经典,建议收藏)
34 0
|
27天前
|
XML 存储 Java
Spring重要类解析
Spring重要类解析
20 0
|
1月前
|
机器学习/深度学习 算法
【数学建模竞赛】评价类赛题常用算法解析
【数学建模竞赛】评价类赛题常用算法解析
32 0
|
3月前
|
Java C#
C# 面向对象编程解析:优势、类和对象、类成员详解
OOP代表面向对象编程。 过程式编程涉及编写执行数据操作的过程或方法,而面向对象编程涉及创建包含数据和方法的对象。 面向对象编程相对于过程式编程具有几个优势: OOP执行速度更快,更容易执行 OOP为程序提供了清晰的结构 OOP有助于保持C#代码DRY("不要重复自己"),并使代码更易于维护、修改和调试 OOP使得能够创建完全可重用的应用程序,编写更少的代码并减少开发时间 提示:"不要重复自己"(DRY)原则是有关减少代码重复的原则。应该提取出应用程序中常见的代码,并将其放置在单一位置并重复使用,而不是重复编写。
51 0
|
11天前
|
Java
Java 15 神秘登场:隐藏类解析未知领域
Java 15 神秘登场:隐藏类解析未知领域
15 0
|
28天前
|
存储 程序员 编译器
【C++ 模板类与虚函数】解析C++中的多态与泛型
【C++ 模板类与虚函数】解析C++中的多态与泛型
46 0
|
30天前
|
Python
Python类与对象:深入解析与应用
本文介绍了Python中的核心概念——类和对象,以及它们在面向对象编程中的应用。类是用户定义的类型,描述具有相同属性和行为的对象集合;对象是类的实例,具备类的属性和方法。文章通过示例讲解了如何定义类、创建及使用对象,包括`__init__`方法、属性访问和方法调用。此外,还阐述了类的继承,允许子类继承父类的属性和方法并进行扩展。掌握这些概念有助于提升Python编程的效率和灵活性。
|
1月前
|
存储 安全 程序员
【C++ 包装器类 智能指针】完全教程:std::unique_ptr、std::shared_ptr、std::weak_ptr的用法解析与优化 — 初学者至进阶指南
【C++ 包装器类 智能指针】完全教程:std::unique_ptr、std::shared_ptr、std::weak_ptr的用法解析与优化 — 初学者至进阶指南
68 0
|
1月前
|
消息中间件 Linux API
跨进程通信设计:Qt 进程间通讯类全面解析
跨进程通信设计:Qt 进程间通讯类全面解析
80 0
|
1月前
|
域名解析 缓存 网络协议
探索Qt 网络编程:网络地址与服务类全解析
探索Qt 网络编程:网络地址与服务类全解析
55 0

推荐镜像

更多