在函数中盲目定义成员变量

Define member variables in functions blindly

本文关键字:成员 变量 定义 盲目 函数      更新时间:2023-10-16

我当前的任务有点问题。基本上,我得到一个XML文件,并试图解析它以获取关键信息。例如,有些行是这样的:

<IPAddress>123.45.67</IPAddress>

我得到的值是123.45.67,一点也不坏。我被告知不要使用XML解析器,只需手动解析即可,这非常简单。然而,我对任务的第二部分有问题。基本上,我将创建一个具有某些成员变量的类,并根据我解析的值声明它们。假设这个类叫Something有一个成员变量叫IPAddress。然后我将IPAddress的值更新为123.45.67,因此当有人调用某些东西时。在主方法中的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语句就很烦人了。还有其他方法可以访问类中的成员变量吗?对不起,如果我的问题很长,我只是想确保一切需要理解的问题提供!请让我知道,如果有什么重要的,可能没有应该添加。

非常感谢!

这可能被认为是糟糕的风格,但我通常只是这样做:

// 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;