在我们的游戏中,经常需要将策划的数值配置成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. PMP(第六版)中的沟通方法总结与对比

  2. React后台管理系统-后台接口封装

    1新建文件夹 service ,里边建4个文件,分别是statistic-service.jsx 首页数据统计接口, user-service.jsx用户接口, product-service.jsx ...

  3. 解决使用Application Loader上传ipa提示“上传appstore失败”

    试了好多次使用Application Loader上传ipa,一直提示上传失败,用其他mac电脑却可以,那就是环境有问题,笔者试过重装xcode,都无法解决问题, 查看日志类似是jdk版本问题,换了所 ...

  4. VueX源码分析(3)

    VueX源码分析(3) 还剩余 /module /plugins store.js /plugins/devtool.js const devtoolHook = typeof window !== ...

  5. JSP出现"属性值[request.getParameter("myMessage")]引用["],在值内使用时必须被转义"的解决方法

    写JSP时出现属性值[request.getParameter("myMessage")]引用["],在值内使用时必须被转义. 源代码: <jsp:setPrope ...

  6. Linux ps与top命令

    Linux ps与top命令 这两个命令都是查看系统进程信息的命令,但是用处有点儿不同 1.ps命令--提供系统过去信息的一次性快照 也就是说ps命令能够查看刚刚系统的进程信息  命令:ps aux或 ...

  7. ES6 的解构赋值前每次都创建一个对象吗?会加重 GC 的负担吗?

    本文来源于知乎上的一个提问. 为了程序的易读性,我们会使用 ES6 的解构赋值: function f({a,b}){} f({a:1,b:2}); 这个例子的函数调用中,会真的产生一个对象吗?如果会 ...

  8. 3 个用于数据科学的顶级 Python 库

    使用这些库把 Python 变成一个科学数据分析和建模工具. Python 的许多特性,比如开发效率.代码可读性.速度等使之成为了数据科学爱好者的首选编程语言.对于想要升级应用程序功能的数据科学家和机 ...

  9. PHP实现消息推送

    我们做web的时候偶尔会遇到消息推送,如图示例(红框位置) 当我们遇到这种功能要如何开发呢?下边将我了解的两种方法整理一下: 一.ajax轮询,定时去请求服务器数据 通过观察thinkphp官网貌似也 ...

  10. mysql面试题:字段中@之前字符相同且大于等于2条的所有记录

    公司发了一张面试题给我,题目如下: 在test数据库中有个flow_user表,找出email字段中@之前字符相同且大于等于2条的所有记录 答案: select substring_index(`em ...