Cocos2d C ++ parses CSV and cocos2d parses csv
1. What is CSV
Success,
It is a file that uses English ',' as the separator. This structure is a bit like the structure of a database table, because it is very simple, so it has a wide range of applicability, Excel can export CSV, Sqlite and other databases can also export CSV.
In game development, this file is generally edited for planning. After modifying the value, it is easy to test and you do not need to compile the game. I personally prefer script development, allowing the planner to directly modify the script, saving the CSV file.
2. parse CSV
There are many versions on the network, which are too complicated to write. Some cannot work very well. I think the good version only depends on the stl of C ++, and the returned value should be a two-dimensional string array vector <string>. I wrote the following:
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;}
Use (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