Cocos2d C++ 解析CSV

1.什么是CSV


Id,主题关卡名字,主题背景音乐,主题背景图片,1,关卡名字1,test.mp3,test.png,2,关卡名字2,3,关卡名字3,

就是以英文‘,’作为分隔符的文件。这种结构有点像数据库表的结构,因为非常简单,所以适用范围比较广,Excel可以导出CSV,sqlite 等数据库也可以导出CSV。

在游戏开发中,这个文件一般给策划来进行编辑,修改数值后很容易测试,不需要编译游戏。我个人是比较喜欢脚本开发,让策划直接修改脚本,省去CSV这一部。


2.解析CSV


网络上有很多版本,写的都太复杂了。有些还不能很好工作。我觉得好的版本是只依赖C++ 的stl的,而且返回的值应该是一个二维的字符串数组vector<vector<string> >。我写的如下:

CSVParser.h

#ifndef TestConfig_CppCSV_h
#define TestConfig_CppCSV_h

#include <fstream>
#include <string>
#include <iostream>
#include <vector>

using namespace std;

class CSVParser{
public:
    CSVParser(const char* fileName);
    ~CSVParser();
    
    vector<vector<string> > data;
    static string Trimstring(string& str);
};

#endif

CSVParser.cpp


#include "CSVParser.h"

CSVParser::CSVParser(const char* fileName){
    data.clear();
    
    std::ifstream file(fileName);
    std::string line;
    //get each line string
    while (getline(file,line))
    {
        istringstream sin(line);
        vector<string> fields;
        string field;
        while (getline(sin,field,',')) {
            fields.push_back(CSVParser::Trimstring(field));
        }
        data.push_back(fields);
    }
    file.close();
}

CSVParser::~CSVParser(){
    data.clear();
}

string CSVParser::Trimstring(string& str)
{
    //replace \r
    string::size_type i = 0,j = 0;
    
    j = str.find_first_of("\n\r",i);
    if (j < str.size()){
        str.erase(j,1);
    }
    
    j = str.find_first_of("\r",1);
    }
    
    return str;
}

使用(cocos2d -x 3.x 版本):
CSVParser parser = CSVParser(FileUtils::getInstance()->fullPathForFilename("test.csv").c_str());
    vector<vector<string> > data = parser.data;


http://www.waitingfy.com/archives/1722

相关文章

    本文实践自 RayWenderlich、Ali Hafizji 的文章《...
Cocos-code-ide使用入门学习地点:杭州滨江邮箱:appdevzw@1...
第一次開始用手游引擎挺激动!!!进入正题。下载资源1:从C...
    Cocos2d-x是一款强大的基于OpenGLES的跨平台游戏开发...
1.  来源 QuickV3sample项目中的2048样例游戏,以及最近《...
   Cocos2d-x3.x已经支持使用CMake来进行构建了,这里尝试...