我的当前任务有点问题。基本上,我得到一个XML文件,并试图解析它的关键信息。例如,某些行将是这样的:
<IPAddress>123.45.67</IPAddress>
我的价值是123.45.67,一点也不差。我被告知不要使用XML解析器,只需手动解析,这非常简单。但是,我遇到了第二部分任务的问题。基本上,我要创建一个包含某些成员变量的类,并根据我解析的值声明它们。所以我们假设这个类名为Something,并且有一个名为IPAddress的成员变量。然后我将IPAddress的值更新为123.45.67,所以当有人在main方法中调用Something.IPAddress时,它返回123.45.67。这是我最初的尝试:
#include <iostream>
#include <fstream>
#include <string>
#include <sys/stat.h>
using namespace std;
class Something
{
public:
string location;
string IPAddress;
string theName;
int aValue;
//loop through the array from the method below
void fillContent(string* array)
{
for(int i = 0; i < array->size(); i++)
{
string line = array[i];
if((line.find("<") != std::string::npos) && (line.find(">")!= std::string::npos))
{
unsigned first = line.find("<");
unsigned last = line.find(">");
string strNew = line.substr (first + 1, last - first - 1); //this line will get the key, in this case, "IPAddress"
unsigned newfirst = line.find(">");
unsigned newlast = line.find_last_of("<");
string strNew2 = line.substr(newfirst + 1, newlast - newfirst - 1); //this line will get the value, in this case, "123.45.67"
if(strNew == "IPAddress")
{
IPAddress = strNew2; //set the member variable to the IP Address
}
}
}
}
//this method will create an array where each element is a line from the xml
void fillVariables()
{
string line;
ifstream myfile ("content.xml");
long num = //function that gets size that I didn't add to make code shorter!;
string *myArray;
myArray = new string[num];
string str1 = "";
string strNew2 = "";
int counter = 0;
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
myArray[counter] = line;
counter++;
}
myfile.close();
}
fillContent(myArray);
}
};
int main(int argc, char* argv[])
{
Something local;
local.fillVariables();
cout << local.IPAddress<< endl; // should return "123.45.67"
return 0;
}
现在这确实做了我想做的事情,但是,你可以看到我需要if语句。假设我有至少20个这样的成员变量,有20个if语句会很烦人,只是不满意。有没有其他方法可以以某种方式从类中访问成员变量?对不起,如果我的问题很长,我只是想确保提供了解问题所需的一切!如果有任何可能不存在的重要事项应该添加,请告诉我。
非常感谢!
答案 0 :(得分:0)
这可能被认为是不好的风格,但我通常只会这样做:
// at the top of the 'fillContent' function
std::map<string, string*> varmap{
{"IPAddress", &IPAddress},
{"AnotherField", &AnotherField}
};
// If you're not using C++11, you can also try:
// std::map<string, string*> varmap;
// varmap["IPAddress"] = &IPAddress;
// varmap["AnotherField"] = &AnotherField;
// parsing code goes here
*varmap[strNew] = strNew2;