在我们的游戏中,经常需要将策划的数值配置成csv文件,所以解析csv文件就是一个很common的logic,

例如如下csv文件:

下面是一个基于cocos2dx 2.2.4的实现类:

#ifndef __Cell__GCCsvHelper__
#define __Cell__GCCsvHelper__ #include <iostream>
#include "cocos2d.h"
#include <vector> USING_NS_CC; class GCCsvHelper
{
public:
GCCsvHelper();
~GCCsvHelper(); bool openAndResolveFile(const char *fileName); const char *getData(unsigned int rowIndex, unsigned int colIndex); inline int getColLength() { return m_colLength; }
inline int getRowLength() { return data.size(); } private:
const std::string m_seperator;
std::vector<std::vector<std::string> > data; //cols length
int m_colLength; void rowSplit(std::vector<std::string> &rows, const std::string &content, const char &rowSeperator);
void fieldSplit(std::vector<std::string> &fields, std::string line); //获取带引号的字段
int getFieldWithQuoted(const std::string &line, std::string& field, int index); //获取无引号的字段
int getFieldNoQuoted(const std::string &line, std::string &field, int index);
}; #endif /* defined(__Cell__GCCsvHelper__) */
#include "GCCsvHelper.h"

GCCsvHelper::GCCsvHelper()
:m_seperator(",")
,m_colLength()
{ } GCCsvHelper::~GCCsvHelper()
{ } #pragma region reselove the content begin... bool GCCsvHelper::openAndResolveFile(const char *fileName)
{
std::string pathKey = CCFileUtils::sharedFileUtils()->fullPathForFilename(fileName);
unsigned char* pBuffer = NULL;
unsigned long bufferSize = ;
pBuffer = CCFileUtils::sharedFileUtils()->getFileData(pathKey.c_str(), "r", &bufferSize); std::string tmpStr = (char*)pBuffer;
std::string fileContent = tmpStr.substr(, bufferSize); std::vector<std::string> line;
rowSplit(line, fileContent, '\n');
for (unsigned int i = ; i < line.size(); ++i) {
std::vector<std::string> fieldVector;
fieldSplit(fieldVector, line[i]);
data.push_back(fieldVector);
m_colLength = std::max(m_colLength, (int)fieldVector.size());
} return true;
} void GCCsvHelper::rowSplit(std::vector<std::string> &rows, const std::string &content, const char &rowSeperator)
{
std::string::size_type lastIndex = content.find_first_not_of(rowSeperator, );
std::string::size_type currentIndex = content.find_first_of(rowSeperator,lastIndex); while (std::string::npos != currentIndex || std::string::npos != lastIndex) {
rows.push_back(content.substr(lastIndex, currentIndex - lastIndex));
lastIndex = content.find_first_not_of(rowSeperator, currentIndex);
currentIndex = content.find_first_of(rowSeperator, lastIndex);
}
} void GCCsvHelper::fieldSplit(std::vector<std::string> &fields, std::string line)
{
if (line[line.length() - ] == '\r') {
line = line.substr(, line.length() - );
} std::string field;
unsigned int i = , j = ;
while (j < line.length()) {
if (line[i] == '"') {
//有引号
j = getFieldWithQuoted(line, field, i);
} else {
j = getFieldNoQuoted(line, field, i);
} fields.push_back(field);
i = j + ; //解析下一个field, +1为了跳过当前的分隔符
}
} int GCCsvHelper::getFieldWithQuoted(const std::string &line, std::string &field, int i)
{
unsigned int j = ;
field = std::string();
if (line[i] != '"') {
//不是引号起始,有问题
CCLOGERROR("start char is not quote when call %s", __FUNCTION__);
return -;
} for (j = i + ; j < line.length() - ; ++j) {
if (line[j] != '"') {
//当前char不为引号,则是field内容(包括逗号)
field += line[j];
} else {
//遇到field结束时的引号,可以返回
return j;
break;
}
} if (j == line.length()) {
//没有找到成对的结束引号
CCLOGERROR("resoleve the line error: no pair quote, line:%s, field:%s, start index:%d", line.c_str(), field.c_str(), i);
} return j;
} int GCCsvHelper::getFieldNoQuoted(const std::string &line, std::string &field, int index)
{
unsigned int j = ;
//找到下一个分隔符位置
j = line.find_first_of(m_seperator, index);
if (j > line.length()) {
j = line.length();
} field = std::string(line, index, j - index); return j;
} #pragma region end. ///////search data
const char *GCCsvHelper::getData(unsigned int rowIndex, unsigned int colIndex)
{
if (rowIndex >= getRowLength() || colIndex >= getColLength()) {
return "";
} if (colIndex >= data[rowIndex].size()) {
return "";
} return data[rowIndex][colIndex].c_str();
}

Test Case:

void CsvHelperTesterScene::onEnter()
{
CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize(); GCCsvHelper *csv = new GCCsvHelper();
csv->openAndResolveFile("test.csv"); std::string line = "";
for (int i = ; i < csv->getRowLength(); ++i) {
for (int j = ; j < csv->getColLength(); ++j) {
line += csv->getData(i, j);
line += ";";
} CCLabelTTF *pLbl = CCLabelTTF::create(line.c_str(), "Arial", );
pLbl->setColor(ccc3(, , ));
pLbl->setPosition(ccp(visibleSize.width / , visibleSize.height - - i * ));
addChild(pLbl); line = "";
} delete csv;
}

测试结果:

[cocos2dx utils] cocos2dx读取,解析csv文件的更多相关文章

  1. 如何用Java解析CSV文件

    首先看一下csv文件的规则: csv(Comma Separate Values)文件即逗号分隔符文件,它是一种文本文件,可以直接以文本打开,以逗号分隔.windows默认用excel打开.它的格式包 ...

  2. .NET 上传并解析CSV文件存库

    1.前端: 放置浏览按钮 <div class="row inner_table text-center"> <input id="fileId&quo ...

  3. java opencsv解析csv文件

    记一次使用opencsv解析csv文件时碰到的坑 最近在开发过程中需要解析csv文件,公司用的解析工具是opencsv,在根据opencsv的官方文档去解析时发现csv文件中含有繁体字,使用其自带的C ...

  4. C语言读取写入CSV文件 [一]基础篇

    本系列文章目录 [一] 基础篇 [二] 进阶篇--写入CSV [三] 进阶篇--读取CSV 什么是CSV? CSV 是一种以纯文本形式存储的表格数据,具体介绍如下(来自维基百科): 逗号分隔值(Com ...

  5. php解析.csv文件

    public function actionImport() { //post请求过来的 $fileName = $_FILES['file']['name']; $fileTmpName = $_F ...

  6. boost::property_tree读取解析.xml文件

    boost::property_tree读取解析.xml文件 1)read_xml 支持中文路径  boost::property_tree::wptree wpt;    std::locale:: ...

  7. boost::property_tree读取解析ini文件--推荐

    boost::property_tree读取解析ini文件 #include "stdafx.h" #include <iostream> #include <b ...

  8. 读取gzmt.csv文件,计算均值及概率

    问题: 读取gzmt.csv文件所有数据,选取收盘价格(倒数第二列),计算20天均值,权重取成交量(选做:时间权重为半衰期为15天):将该均值修剪为超过600的都设置为1000,并打印出该均值超过55 ...

  9. jmeter读取本地CSV文件

    用jmeter录制考试上传成绩等脚本时,出现的问题及解决方法如下: 1.beanshell前置处理器,不能读取本地csv文件里的数据: 方法一: 在beanshell里不能直接从本地的csv文件里读取 ...

随机推荐

  1. frombuffer的用法

    函数原型为:numpy.ma.frombuffer(buffer, dtype=float, count=-1, offset=0) import numpy s = 'hello world' pr ...

  2. C# 常用函数和方法集汇总

    1.DateTime 数字型 System.DateTime currentTime=new System.DateTime(); 1.1 取当前年月日时分秒 currentTime=System.D ...

  3. HashMap原理以及自己实现HashMap

    1.HashMap是什么? HashMap是java常用来存储键值对的数据结构,它是以key/value的形式存储的,它不是线程安全的,Key可以为null值. 2.HashMap的实现原理 Hash ...

  4. 如何用eclipse运行导入的maven项目

    1.配置jdk系统环境变量.找到安装的jdk的安装目录,新建系统环境变量,变量名为JAVA_HOME(作为一个引用),变量值为该路径. 找到Path,将%JAVA_HOME%/bin; 添加到变量值的 ...

  5. Bomb HDU - 3555 (数位DP)

    Bomb HDU - 3555 (数位DP) The counter-terrorists found a time bomb in the dust. But this time the terro ...

  6. 【Isamaru, Hound of Honda】SVN常用命令补遗

    一些常用的 就是svn commit的时候 都必须是最新版本的东西 不能不是,但是其实只是.svn在控制,所以可以update到最新版本再svn merge -r 20:10 将版本10和20的融合, ...

  7. poj 1258 建光迁问题 最小生成树

    题意:给全村建光纤,求花费最小 思路:最小生成树,树相对于图来说就是没有环 m用来存图 v判断是否访问 low用来存两点间的最短距离 给low赋值  for(i=1;i<=n;i++){if(i ...

  8. 字符编码,ASCII、Unicode与UTF-8的理解

    首先我们先要明白的两点是:1.计算机中的信息都是由二进制的0和1储存的:2.我们再计算机屏幕上看到的各种字符都是计算机系统按照一定的规则将二进制数字转换而来的. 一.基本概念. 1.字符集(chars ...

  9. EF上下文对象创建之线程内唯一

    在一次请求中,即一个线程内,若是用到EF数据上下文对象,就创建一个,那么会造成数据混乱,每次创建的对象执行相应的数据库操作,此同时,其他的EF对象内获得的数据可能已经是“过期”的了.即这个数据已经变动 ...

  10. Python linecache模块

    Table of Contents 1. linecache 1.1. 其它 2. 参考资料 linecache 今天分享一个python的小模块: linecache, 可以用它方便地获取某一文件某 ...