一个操作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-03 08:40:08

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

qt之窗口换肤(一个qss的坑:当类属性发现变化时需要重置qss)

1.相关文章 Qt 资源系统qt的moc,uic,rcc命令的使用 2.概要    毕业两年了,一直使用的是qt界面库来开发程序,使用过vs08.10.13等开发工具,并安装了qt的插件,最近在做客户端换肤功能,所以就对qt的qrc做了点儿研究,我是一个实干派(可能有点儿虚),相对于看文档来说.本文开头我就给出了两篇博客,这两篇博客对我理解qrc这个东西有很大的帮助,接下来我就简单分析下我的理解. 首先说明下qrc是qt的东西,而不属于vs,这也很容易证明,那就是vs的工程师不识别qrc文件的,

JAVA操作JSON格式数据

由于近些日子公司在弄微信项目,而微信官方API所提供的接口当中,有些需要以POST方式进行请求,且数据传输格式要求为JSON格式数据,之前没怎么研究过,而且传递的数据格式相对也比较简单,所以直接都是采用的字符串拼接的方式进行组装的,之后再用String.format格式化一下就好了. //需要提交的json数据 String jsonData = "{\"openid\":\"%s\",\"to_groupid\":%d}";

一个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

java格式处理工具类

import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.math.BigInteger; import java.text.Par

weixin4j开发—为大家提供一个获取Weixin对象的工具类

如果大家下载了weixin4j的话,那么这个工具类对大家使用weixin4j将是一个非常好用的工具类. 首先我创建了一个数据表,来存放access_token CREATE TABLE `t_token` ( `id` int(11) NOT NULL AUTO_INCREMENT, `access_token` varchar(120) NOT NULL, `expires_in` int(11) NOT NULL, `createTime` datetime NOT NULL, PRIMAR

分享一个简单的简单的SQLHelper类

分享一个简单的简单的SQLHelper类,代码如下: 1 class SqlHelper 2 { 3 public static readonly string connstr = 4 ConfigurationManager.ConnectionStrings["dbConnStr"].ConnectionString; 5 6 public static int ExecuteNonQuery(string cmdText, 7 params SqlParameter[] para

UIViewAdditions(一个很方便使用的工具类吧)

我们在工程中,或多或少的要修改控件的坐标-宽度-高度,于是,经常性的见到大家self.view.frame.origin.x,self.view.frame.size.width.........相当的麻烦,在这里向大家推荐一个比较好的工具类,是UIView的类目,它里面对于求坐标,求高度什么的做了封装,很方便大家调用. @下载链接:点击这里 @.h #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @interfa

一个C#的XML数据库访问类

原文地址:http://hankjin.blog.163.com/blog/static/33731937200942915452244/ 程序中不可避免的要用到配置文件或数据,对于数据量比较小的程序,部署数据库花费的时间就显得浪费了,因此用XML来存储不妨为一个很好的办法,而且结合C#的DataSet,我们可以很轻易的封装出一个代码简单而功能强大的数据访问类XMLConfigconfig.xml<root>  <table1>    <rowName1>hello&l

创建一个提供搜索功能的搜索类(可运行)

/* * 这段代码的主要功能是对于创建索引的后的文件, * 创建一个提供搜索功能的搜索类. * */ package ch2.lucenedemo.process; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Date; import java.util.Iterator; import jav