#pragma warning(disable:4786)
#include <iostream>
#include <fstream>
#include <string>
#include <map>
using namespace std;
class MySection
{
string section;
map<string,string> mapkey;
public:
MySection(string section)
{
this->section = section;
}
bool AddKeyValue(string key,string value)
{
pair<string,string> p(key,value);
mapkey.insert(p);
return true;
}
void Show(ostream &os)
{
os << section << endl;
map<string,string>::iterator it = mapkey.begin();
while(it != mapkey.end())
{
os << "\t" << (*it).first << "=" << (*it).second << endl;
it ++;
}
}
};
class MySelectCollect
{
map<string,MySection> mapsection;
public:
bool AddSection(string strSection)
{
pair<string,MySection> p(strSection,MySection(strSection));
mapsection.insert(p);
return true;
}
MySection * GetSection(string strSection)
{
map<string,MySection>::iterator it = mapsection.find(strSection);
return &((*it).second);
}
void Show(ostream &os)
{
map<string,MySection>::iterator it = mapsection.begin();
while(it != mapsection.end())
{
((*it).second).Show(os);
it ++;
}
}
};
class ReadIni
{
string strPath;
MySelectCollect & collect;
public:
ReadIni(string strPath,MySelectCollect &collect):strPath(strPath),collect(collect){}
void Trim(string &s)
{
if(s != "")
{
s.erase(0,s.find_first_not_of(" "));
if(s != "")
s.erase(s.find_last_not_of(" ") + 1);
}
}
string GetSection(string strText)
{
strText.erase(0,strText.find_first_not_of("["));
strText.erase(strText.find_last_not_of("]")+1);
return strText;
}
void GetPair(string strText,string &key,string &value)
{
int pos = strText.find("=");
key = strText.substr(0,pos);
value = strText.substr(pos+1,strText.length()-pos-1);
Trim(key);
Trim(value);
}
void Process()
{
string strLine = "";
string strSection = "";
string strKey = "";
string strValue = "";
MySection * pSection = NULL;
ifstream in(strPath.c_str());
while(!in.eof())
{
getline(in,strLine);
Trim(strLine);
if(strLine == " ")
continue;
if(strLine.at(0) == '[')
{
strSection = GetSection(strLine);
collect.AddSection(strSection);
pSection = collect.GetSection(strSection);
}
if(strLine.at(0) != '[')
{
GetPair(strLine,strKey,strValue);
pSection->AddKeyValue(strKey,strValue);
}
}
in.close();
}
};
int main()
{
string path = "E:\GAME\bin\mygamelist.ini";
MySelectCollect collect;
ReadIni ri(path,collect);
ri.Process();
collect.Show(cout);
return 0;
}
算法描述:
1.打开ini文件输入流
2.while(输入流非空)
3. strLine <- 读一行字符串
4. strLine 去左右空格
5. if strLine 是空格 then continue
6. if strLine第一个字符是"[",表明是新的section then
7. 获得新section标识串
8. 根据该标识串添加新section
9. 用变量保持住新添加section对象,为佳key-value键值对做准备
10 if strLine第1个字符不是"[",表明是新的key-value对 then
11 获得key及value值
12 用9保持section对象,添加key-value键值对对象
13.end while