jeudi 2 juillet 2020

Config file parser is only returning previous value

I have a small block of code, which is used to read the configuration file and then find for the specific value based on the key. My program now looks something like this:

string readConfigFile(string configKey) {
    cout << "ReadConfigFile\n";
    fstream drConfig("/usr/share/dr_config");
    if(drConfig.is_open()) {
        string line;
        string value;
        while (getline(drConfig, line))
        {
            line.erase(std::remove_if(line.begin(), line.end(), ::isspace), line.end());
            if(line[0] == '#' || line.empty()){
                continue;
            }
            auto delimiterPos = line.find("=");
            auto name = line.substr(0, delimiterPos);
            value = line.substr(delimiterPos + 1);
            // Use this to find a specific string
            if (line.find(configKey) != std::string::npos) {
                cout << value << endl;
            }
        }
        return value;
    } else {
        return "Couldn't open the config file!\n";
    }
}

In my main code I call it something like this:

string num1 = readConfigFile("120");
stringstream geek(num1);
int x = 0;
geek >> x;
cout << "The value of x is " << x << "\n";

string num2 = readConfigFile("100");
stringstream geek(num2);
int y= 0;
geek >> y;
cout << "The value of y is " << y<< "\n";

Supposedly, it should print me number 100 for my int y. But surprisingly, it's printing my previous value which is 120. I am thinking something is wrong in my readConfigFile() method. Can someone guide me through this? How can I get the latest value which is 100?

Aucun commentaire:

Enregistrer un commentaire