天天看點

Cocos2d C++ 解析CSV

1.什麼是CSV

Id,主題關卡名字,主題背景音樂,主題背景圖檔,
1,關卡名字1,test.mp3,test.png,
2,關卡名字2,test.mp3,test.png,
3,關卡名字3,test.mp3,test.png,      

就是以英文‘,’作為分隔符的檔案。這種結構有點像資料庫表的結構,因為非常簡單,是以适用範圍比較廣,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", i);
    if (j < str.size()){
        str.erase(j, 1);
    }
    
    return str;
}      

使用(cocos2d -x  3.x 版本):

CSVParser parser = CSVParser(FileUtils::getInstance()->fullPathForFilename("test.csv").c_str());
    vector<vector<string> > data = parser.data;      

繼續閱讀