1.题目
有文件 config.ini 如下:
[config1]
attribute1 = abc
attribute2 = def
attribute3 = abcde
[config2]
attributex=cat
attributey =dog
attributez= mouse
[config3]
#attribute_alpha = alpha
attribute_beta = beta
attribute_gamma = gamma
其中,config1、config2、config3 为分类,每个分类下有若干属性,要求
输入:分类名、属性名 (如: config1 attribute1)
输出:属性值 (如果是上面的输入,则返回 abc)
要求程序可以忽略每一行中多余的空格,如果一行第一个非空格字符为'#',则视作注释处理
2.代码
在文件 reader.cpp 中有如下代码
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
string trim(string s)
{
if(s.empty())
{
return s;
}
s.erase(0, s.find_first_not_of(" "));
s.erase(s.find_last_not_of(" ") + 1);
return s;
}
int main()
{
//enter group and attribute
cout << "Please Enter Group and Attribute Name: " << endl;
string sgroup = "", sattr = "";
cin >> sgroup >> sattr;
//sign if group or attribute be found
bool isGroupFound = false;
bool isAttributeFound = false;
//check for gourps and attributes
while(sgroup != "#")
{
//open file config.ini
ifstream infile("config.ini", ios::in);
if(!infile)
{
cout << "something error!" << endl;
exit(1);
}
cout << "file opened successfully!" << endl;
//Initialize the Parameters
isGroupFound = false;
isAttributeFound = false;
cout << "Check for Gourps: " << sgroup << endl;
string temp;
while(getline(infile, temp))
{
if(trim(temp) == ("[" + sgroup + "]"))
{
cout << "Group Matched!" << endl;
isGroupFound = true;
break;
}
}
if(!isGroupFound)
{
cout << "Group Not Found!" << endl;
}
else
{
cout << "Check for Attributes: " << sattr << endl;
while(getline(infile, temp))
{
temp = trim(temp);
//commit - continue; the end of group - break;
if(temp[0] == '#')
{
continue;
}
else if(temp[0] == '[')
{
break;
}
//if attrname is equal to sattr then print attrvalue (word after '=')
string attrname = "";
string attrvalue = "";
for(int i = 0; i < temp.length(); i++)
{
if(temp[i] != '=')
{
attrname += temp[i];
continue;
}
if(trim(attrname) == sattr)
{
cout << "Attribute Matched!" << endl;
//read attrvalue
i++;
while(i < temp.length())
{
attrvalue += temp[i++];
}
cout << "\nValue is " << trim(attrvalue) << "\n\n";
isAttributeFound = true;
break;
}
else
{
break;
}
}
if(isAttributeFound)
{
break;
}
}
if(!isAttributeFound)
{
cout << "Attribute Not Found!" << endl;
}
}
infile.close();
cout << "File Closed." << endl;
//Input next group and attribute
cin >> sgroup >> sattr;
}
cout << "file closed" << endl;
return 0;
}
3.makefile文件
在同一目录下有文件makefile,内容如下:
conf_reader: reader.o
g++ -o conf_reader reader.o
reader.o: reader.cpp
g++ -c reader.cpp
clean:
rm -rf *.o conf_reader
4.运行结果
输入 make 命令,生成文件 conf_reader,输入下面的命令启动程序
./conf_reader
启动程序后的一个运行示例如下

END
本文介绍了一个使用C++编写的程序,用于解析配置文件config.ini,并根据输入的分类名和属性名获取对应的属性值。程序能够忽略多余空格、处理注释行,并在配置文件中查找指定的组和属性。
1212

被折叠的 条评论
为什么被折叠?



