试图读取配置文件

时间:2012-12-19 17:36:07

标签: c++

抱歉提前格式化。想不出来......

我正在通过参数

将配置文件传递给程序

我正在尝试从特定参数中读取值

我有一个cofigReader类,其中包含以下方法,用于在给定特定参数的情况下从配置文件返回字符串

我的问题,

它永远不会找到参数。发现是0或-1 ....

string configReader::value(string config_file, string parameter)
{
    string value;
    char config_delimiter = '=';
    size_t found;
    file.open(config_file);
    std::string line;
    bool param_found = false;
    while(param_found == false){
        while (!file.eof())
        {       
            getline(file,line);
            logger.writetolog("INFO","Looking for " + parameter +
                         " on line "+ line); 
            found = line.find(parameter);
            logger.writetolog("INFO",int(found));
            if(found!=string::npos){
                param_found = true;
            }
        }
        param_found = true;
    }
    if (found!=string::npos)
    {   
        size_t a = line.find(config_delimiter)+1;
        logger.writetolog("INFO","Found" + parameter + 
                   "splitting string at delimter" + config_delimiter + 
                   " and return right side value");     
        value = line.substr(a);
        return value;
    }
    else
    {
        return value;
    }
    file.close();
}

更多信息。配置文件如下所示。

toemail=someemailaddress@gmail.com
outputdir=C:\tmp

使用的configReader类

//attempt to parse out the required parameters for the program
string toemail = config.value(configFileArg,"toemail"); 

它总是返回空白

2 个答案:

答案 0 :(得分:3)

找到匹配后,while (!file.eof())循环会继续,覆盖您稍后检查的found的值。

您可以通过将循环更改为

来解决此问题
bool param_found = false;
while (!param_found && !file.eof()) {       
    if (getline(file,line)) {
        break;
    }
    logger.writetolog("INFO","Looking for " + parameter +" on line "+ line); 
    found = line.find(parameter);
    logger.writetolog("INFO",int(found));
    if(found!=string::npos){
        param_found = true;
        break;
    }
}

代替。 (请注意,此代码会删除while(param_found == false)循环。正如sftrabbit指出的那样,该循环是不必要的。)

答案 1 :(得分:2)

写循环的惯用方法是:

bool param_found = false;

while (std::getline(file,line)) //<-- this is idiomatic loop!
{                               //successfully read OR exit from the loop

    logger.writetolog("INFO","Looking for " + parameter +" on line "+ line); 
    found = line.find(parameter);
    logger.writetolog("INFO",int(found));
    if(found!=string::npos){
        param_found = true;
        break;
    }
}

编写循环时不应使用eof()

这两个主题详细讨论了这个问题。