一个操作cvs格式的c++类

经常需要使用excel,或者把有的数据用excel打开,程序可以生成cvs格式的文件,这样就可以excel打开并处理了,于是找了一个处理cvs的c++类跟大家分享

代码出处找不到了:

 

代码如下:

 

StringParser.h

#pragma once
#include <process.h>
#include <Windows.h>
#include <map>
#include <vector>
#include <queue>
#include <set>
#include <string>
#include <list>

typedef char                    i8;
typedef unsigned char           u8;
typedef short                  i16;
typedef unsigned short          u16;
typedef long int                i32;
typedef unsigned long           u32;

namespace StringParser{

//从分隔符中获得数据
inline int GetParamFromString(std::string Str, std::vector<i32>& IntVec, char Delim = ',')
{
    char* p = strtok((char*)Str.c_str(), &Delim);
    while (p)
    {
        IntVec.push_back(atoi(p));
        p = strtok(NULL, &Delim);
    }
    return IntVec.size();
}

inline int GetParamFromString(std::string Str, std::vector<float>& FloatVec, char Delim = ',')
{
    char* p = strtok((char*)Str.c_str(), &Delim);
    while (p)
    {
        FloatVec.push_back(atof(p));
        p = strtok(NULL, &Delim);
    }
    return FloatVec.size();
}

inline int GetParamFromString(std::string Str, std::vector<u32>& uiIntVec, char Delim = ',')
{
    char* p = strtok((char*)Str.c_str(), &Delim);
    while (p)
    {
        uiIntVec.push_back(strtoul(p, NULL, 10));
        p = strtok(NULL, &Delim);
    }
    return uiIntVec.size();
}

inline int GetParamFromString(std::string Str, std::vector<std::string>& StringVec, char Delim = ',')
{
    char* p = strtok((char*)Str.c_str(), &Delim);
    while (p)
    {
        std::string buffer = p;
        StringVec.push_back(buffer);
        p = strtok(NULL, &Delim);
    }
    return StringVec.size();
}

//以左右符号得到括号中的数据ex:[3.1415;0.125][1000;9999]
template<typename T>
int GetParamFromArea(std::string Str, std::vector<std::vector<T> >& IntVec, char left = '[', char right = ']', char Delim = ';')
{
    char* pTarget = (char*)Str.c_str();
    for (;;)
    {
        char* pLeft = strchr(pTarget, left);
        char* pRight = strchr(pTarget, right);
        if (pLeft && pRight)
        {
            std::string strbuff;
            strbuff.insert(0, ++pLeft, pRight-pLeft);

            std::vector<T> Intbuff;
            if (GetParamFromString(strbuff, Intbuff, Delim))
            {
                IntVec.push_back(Intbuff);
            }
            pTarget = ++pRight;
        }
        else
        {
            break;
        }
    }
    return IntVec.size();
}

};

CCSVOperator.h

 

#pragma once
#include "StringParser.h"

class CCSVOperator
{

public:
    CCSVOperator(){};
    ~CCSVOperator(){};
    CCSVOperator(const char* path);

    bool LoadCSV(const char* path);
    bool SaveCSV(const char* path = NULL);

    bool GetInt(u32 uiLine, u32 uiRow, int& iValue);
    bool GetFloat(u32 uiLine, u32 uiRow, float& fValue);
    std::string* GetString(u32 uiLine, u32 uiRow);
    bool SetNumber(u32 uiLine, u32 uiRow, int iValue);
    bool SetNumber(u32 uiLine, u32 uiRow, float fValue);
    bool SetString(u32 uiLine, u32 uiRow, const char* pStr);
    std::map<u32, std::map<u32, std::string> >& GetCSVMap(){return m_StringKeyMap;}

protected:
    std::string m_CSVName;
    std::map<u32, std::map<u32, std::string> > m_StringKeyMap;
public:
	int indexOfLines;	//行数
	int indexOfColumn;	//列数,有可能出现列长不一样的情况

};

 

 

 

CSVOperator.cpp

#include "CSVOperator.h"

//////////////////////////////////////////////////////////////////////////
//CSV operator

CCSVOperator::CCSVOperator(const char* path)
{
    LoadCSV(path);
}

bool CCSVOperator::LoadCSV(const char* path)
{
	 indexOfLines = 0;
	 indexOfColumn = 0;
    FILE* pfile = fopen(path, "r");
    if (pfile)
    {
        fseek(pfile,0,SEEK_END);
        u32 dwsize = ftell(pfile);
        rewind(pfile);// 指针回到文件开头

        char* filebuffer = new char[dwsize];
        fread(filebuffer, 1, dwsize, pfile);

        std::map<u32, std::string> StringMap;
        char* pBegin = filebuffer;
        char* pEnd = strchr(filebuffer, '\n');//查找换行首次出现的位置
        u32 uiIndex = 1;
        while (pEnd != NULL)
        {
            std::string strbuff;
            strbuff.insert(0, pBegin, pEnd-pBegin);
            if (!strbuff.empty())
            {
                StringMap[uiIndex] = strbuff;
            }
            pBegin = pEnd + 1;
            pEnd = strchr(pEnd + 1, '\n');
            ++uiIndex;
        }

		indexOfLines = uiIndex - 1;

        delete[] filebuffer;

        std::map<u32, std::string>::iterator iter = StringMap.begin();
        for (; iter != StringMap.end(); ++iter)
        {
            std::vector<std::string> StringVec;
            std::map<u32, std::string> l_StringMap;
            StringParser::GetParamFromString(iter->second, StringVec);

			if (indexOfColumn< StringVec.size())
			{
				indexOfColumn = StringVec.size();//保存最大的列数
			}

            for (int i = 0; i < StringVec.size(); ++i)
            {
                l_StringMap[i+1] = StringVec.at(i);
            }

            m_StringKeyMap[iter->first] = l_StringMap;
        }
        fclose(pfile);
        m_CSVName = path;
        return true;
    }

    return false;
}

bool CCSVOperator::GetInt(u32 uiLine, u32 uiRow, int& iValue)
{
    std::string* pKey = GetString(uiLine, uiRow);
    if (pKey)
    {
        iValue = atoi(pKey->c_str());
        return true;
    }
    else
    {
        return false;
    }
}

bool CCSVOperator::GetFloat(u32 uiLine, u32 uiRow, float& fValue)
{
    std::string* pKey = GetString(uiLine, uiRow);
    if (pKey)
    {
        fValue = atof(pKey->c_str());
        return true;
    }
    else
    {
        return false;
    }
}

std::string* CCSVOperator::GetString(u32 uiLine, u32 uiRow)
{
    std::map<u32, std::map<u32, std::string> >::iterator iterLine = m_StringKeyMap.find(uiLine);
    if (iterLine != m_StringKeyMap.end())
    {
        std::map<u32, std::string>& rStringMap = iterLine->second;
        std::map<u32, std::string>::iterator iterRow = rStringMap.find(uiRow);
        if (iterRow != rStringMap.end())
        {
            return &iterRow->second;
        }
        else
        {
            return NULL;
        }
    }
    else
    {
        return NULL;
    }
}

bool CCSVOperator::SetNumber(u32 uiLine, u32 uiRow, int iValue)
{
    std::string* pKey = GetString(uiLine, uiRow);
    if (pKey)
    {
        char buffer[100];
        memset(buffer, 0, sizeof(buffer));
        sprintf(buffer, "%d", iValue);
        pKey->clear();
        *pKey = buffer;
        return true;
    }
    else
    {
        return false;
    }
}

bool CCSVOperator::SetNumber(u32 uiLine, u32 uiRow, float fValue)
{
    std::string* pKey = GetString(uiLine, uiRow);
    if (pKey)
    {
        char buffer[100];
        memset(buffer, 0, sizeof(buffer));
        sprintf(buffer, "%d", fValue);
        pKey->clear();
        *pKey = buffer;
        return true;
    }
    else
    {
        return false;
    }
}

bool CCSVOperator::SetString(u32 uiLine, u32 uiRow, const char* pStr)
{
    std::string* pKey = GetString(uiLine, uiRow);
    if (pKey)
    {
        pKey->clear();
        *pKey = pStr;
        return true;
    }
    else
    {
        return false;
    }
}

bool CCSVOperator::SaveCSV(const char* path)
{
    if (path != NULL)
    {
        m_CSVName = path;
    }

    FILE* pfile = fopen(m_CSVName.c_str(), "w");
    if (pfile)
    {
        std::map<u32, std::map<u32, std::string> >::iterator iter = m_StringKeyMap.begin();
        for (; iter != m_StringKeyMap.end(); ++iter)
        {
            std::map<u32, std::string>& rStringMap = iter->second;
            std::map<u32, std::string>::iterator it = rStringMap.begin();
            for (; it != rStringMap.end(); ++it)
            {
                std::string key = it->second;
                key += ',';
                fwrite(key.c_str(), 1, key.size(), pfile);
            }
            char Delim = '\n';
            fwrite(&Delim, 1, 1, pfile);
        }
        fclose(pfile);
    }
    else
    {
        return false;
    }

    return true;
}

 

CVS_OP.CPP

 

// CSV_OP.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "CSVOperator.h"
#include <iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{

    CCSVOperator CSVOperator;
    CSVOperator.LoadCSV("画图数据.csv");

	cout<<"line:  "<<CSVOperator.indexOfLines<<endl;
	cout<<"column:  "<<CSVOperator.indexOfColumn<<endl;

    std::string* pString = CSVOperator.GetString(1,600);
    if (pString)
    {
        std::cout<< pString->c_str() << '\n';
    }

    pString = CSVOperator.GetString(2,4);
    if (pString)
    {
        std::cout<< pString->c_str() << '\n';
    }

	//std::string* pString = NULL;
	int j = 0;
	for (int i = 0,nColConut = CSVOperator.indexOfColumn;i < nColConut ; ++i)
	{
		if(pString = CSVOperator.GetString(1,i+1))
		{
			//m_listctrl.InsertColumn(j ,pString->c_str(), LVCFMT_CENTER, 50);  // 添加第1列,
			//cout<<"\t"<<&pString;
			cout<<"\t";
			printf(pString->c_str());
			++j;
		}
	}

//     int _int = 0;
//     if (CSVOperator.GetInt(3,1,_int))
//     {
//         std::cout<< _int <<'\n';
//     }
//
     float _float = 0.0f;
     if (CSVOperator.GetFloat(4,1, _float))
    {
        std::cout<< _float<<'\n';
     }

    system("pause");
	return 0;
}

效果如下:

 

 

时间: 2024-08-02 01:11:59

一个操作cvs格式的c++类的相关文章

jQuery使用Ajax操作JSON格式数据说明

JSON(JavaScript Object Notation)是一种轻量级的数据交换格式.JSON存储了以"Key-Value"为结构的数据.有时候我们需要读取JSON格式的数据文件,在jQuery中可以使用Ajax或者 $.getJSON()方法实现. 先看看API中对$.ajax()的介绍 jQuery.ajax(url,[settings]) 概述 通过 HTTP 请求加载远程数据. jQuery 底层 AJAX 实现.简单易用的高层实现见 $.get, $.post 等.$.

一个方便AJAX开发的通用类

ajax  Name: AJAXRequest Author: HotHeart(xujiwei) Site: http://www.xujiwei.cn/ Blog: http://www.xujiwei.cn/blog/ Copyright (c) 2006, All Rights Reserved 类名:AJAXRequest 版本:0.3 日期:2006-12-18 介绍:AJAXRequest是一个方便AJAX开发的通用类,可以方便地进行一些AJAX中需要的操作,从而简化开发步骤,减少

一个读取xml文件内容的类

xml 一个读取xml文件内容的类 package project.util.xml; import java.io.*;import java.util.*;import javax.servlet.http.*;import org.apache.log4j.*;import org.jdom.*;import org.jdom.input.*; /*** <p>Title: <font color="steelblue" size="10"&

wps表格如何操作筛选格式?

  wps表格是我们办公时经常用的软件,为了方便平时的操作,wps表格中有很多操作技巧,下面来看看wps筛选格式,这个功能能够在整个表格中筛选出需要的内容.便于我们查询.便于我们操作. 软件名称: 金山wps 2003 官方免费完整版 软件大小: 60MB 更新时间: 2014-10-16 方法/步骤 新建一个表格,输入内容,或是已经编辑好的表格.我们需要给表格筛选出内容. 如下图,是我自己输入的内容,如果我们需要筛选出部分内容.点击"自动筛选" 点击数据栏,然后选择自动筛选,整列的第

菜鸟 求解答-html中一个标签如果有两个类属性,里面有些属性冲突,那属性该遵循哪个的

问题描述 html中一个标签如果有两个类属性,里面有些属性冲突,那属性该遵循哪个的 html中一个标签如果有两个类属性,里面有些属性冲突,那属性该遵循哪个的 解决方案 这个是根据你css样式的前后顺序决定的,例如样式表中这样写 .tb{color:red;} .tab{color:green;} 最终的效果是显示绿色,因为tab的写在tb后.你可以换个顺序试试 解决方案二: [vb6.0]一个自用html标签属性存取数据的类 解决方案三: 这个是就近原则 你的标签样式离的最近的那个格式 解决方案

一个java的DES加解密类转换成C#

原文:一个java的DES加解密类转换成C# 一个java的des加密解密代码如下: //package com.visionsky.util; import java.security.*; //import java.util.regex.Pattern; //import java.util.Hashtable; import javax.crypto.*; import javax.crypto.spec.*; import sun.misc.*; /** * des加密解密 */ pu

MFC如何生成一个可串行化的类

一.MFC允许对象在程序运行的整个过程中持久化的串行化机制 (1)串行化是指向持久化存储媒介(如一个磁盘文件)读或写对象的过程. (2)串行化用于在程序运行过程时或之后修复结构化数据(如C++类或结构)的状态. (3)MFC支持CObject类中的串行化,所以,所有继承于CObject的类可以利用CObject的串行化协议. (4)串行化的基本思想:           a.对象必须能将其当前状态写入到持久化存储媒介中,通常用其成员变量实现.           b.对象可以通过读或反序列化从存

一个简单安全的PHP验证码类、PHP验证码_php实例

一,验证码示例 二,php验证码类,secoder.class.php <?php /** * 安全验证码 * * 安全的验证码要:验证码文字扭曲.旋转,使用不同字体,添加干扰码 * * @author 流水孟春 <cmpan(at)qq.com> * @link http://labs.yulans.cn/YL_Security_Secoder * @link http://wiki.yulans.cn/docs/yl/security/secoder */ class YL_Secu

WebClient 请求期间发生异常--在一个非套接字上尝试了一个操作

问题描述 stringstrData="";Streamstream=null;StreamReaderreader=null;WebClientwebClient=null;try{webClient=newWebClient();stream=webClient.OpenRead(newUri(strUri,UriKind.Absolute));reader=newStreamReader(stream);strData=reader.ReadToEnd();}catch(Syst