Cocos2d C ++ 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 depends only on the stl of C ++, and the returned value should be a two-dimensional string array vector. >. I wrote the following:
CSVParser. h
#ifndef TestConfig_CppCSV_h#define TestConfig_CppCSV_h#include
#include
#include
#include
using namespace std;class CSVParser{public: CSVParser(const char* fileName); ~CSVParser(); vector
> data; static string TrimString(string& str);};#endif
CSVParser. cpp
#include CSVParser.hCSVParser::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
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 string::size_type i = 0, j = 0; j = str.find_first_of(, i); if (j < str.size()){ str.erase(j, 1); } j = str.find_first_of(, 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
> data = parser.data;