リストファイル読み込みクラス
これも、全然なんてことはないですが、あると便利なクラス。
1.enemy
# 敵のタイプ,x座標,y座標,z座標, # 一匹目 nomal,-10,0,-5, # 二匹目 nomal,5,0,20, # 三匹目 fly,-2,10,15,
こんなファイルをリストに読み込みます。
ListLoader.h
#pragma once #include <string> #include <vector> using namespace std; /** * リストファイル読み込みクラス */ class CListLoader { public: typedef vector<string> StringList; private: StringList m_vec; public: CListLoader(void){}; ~CListLoader(void){}; void Load(string filepath); StringList GetAll() {return m_vec;} };
ListLoader.cpp
#include ".\listloader.h" #include <fstream> #define __DEBUG_LISTLOADER // デバッグを無効にする場合はコメントアウト // ============================================================================ // プロパティファイル読み込み // @param filepath ファイルパス // @throw ファイルが存在しないとき // ============================================================================ void CListLoader::Load(string filepath) { ifstream ifs(filepath.c_str()); if(ifs.fail()) { throw "Can't open file"; } m_vec.clear(); char tmp[256]; ifs.getline(tmp, 256); while(!ifs.eof()) { string line(tmp); // コメント行 if(line.substr(0, 1).compare("#") != 0) { // 無効行 if(line.length() > 0) { m_vec.push_back(line); } } ifs.getline(tmp, 256); } ifs.close(); } #ifdef __DEBUG_LISTLOADER #include <iostream> // ============================================================================ // 指定したデリミタで文字列を分割し、配列にして返す // @param // @return // ============================================================================ CListLoader::StringList SplitString(string str, string delim) { CListLoader::StringList ret; size_t nDelim = str.find(delim); while(nDelim != -1) { string val = str.substr(0, nDelim); if(val.length() > 0) ret.push_back(val); str = str.substr(nDelim+1); nDelim = str.find(delim); } if(str.length() > 0) ret.push_back(str); return ret; } // ============================================================================ // テストドライバ // ============================================================================ void main() { CListLoader ll; try { ll.Load("1.enemy"); CListLoader::StringList list = ll.GetAll(); CListLoader::StringList::iterator iter = list.begin(); int i = 0; while(iter != list.end()) { cout << i << ":" << endl; CListLoader::StringList strL = SplitString(*iter, ","); for(unsigned int j = 0; j < strL.size(); j++) { cout << " val -> " << strL[j] << endl; } ++iter; i++; } } catch(...) { cout << "ファイル読み込みエラー" << endl; } } #endif
実行結果はこんな感じです。
0: val -> nomal val -> -10 val -> 0 val -> -5 1: val -> nomal val -> 5 val -> 0 val -> 20 2: val -> fly val -> -2 val -> 10 val -> 15