从文件读取和设置变量的更有效方法?

时间:2013-03-18 11:05:32

标签: c++

我有更好的方法从文件读取值并相应地设置它们吗?我可以以某种方式从文件中读取变量名称并在程序中相应地设置它吗?例如,读取BitDepth并将其设置为文件中指定的值?因此,我不必检查此行是否为BitDepth,然后将bit_depth设置为后面的值?

std::ifstream config (exec_path + "/Data/config.ini");
if (!config.good ()) SetStatus (EXIT_FAILURE);
while (!config.eof ()) {
    std::string tmp;
    std::getline (config, tmp);
    if (tmp.find ("=") != 1) {
        if (!tmp.substr (0, tmp.find (" ")).compare ("BitDepth")) {
            tmp = tmp.substr (tmp.find_last_of (" ") + 1, tmp.length ());
            bit_depth = atoi (tmp.c_str ());
        } else if (!tmp.substr (0, tmp.find (" ")).compare ("WindowWidth")) {
            tmp = tmp.substr (tmp.find_last_of (" ") + 1, tmp.length ());
            screen_width = atoi (tmp.c_str ());
        } else if (!tmp.substr (0, tmp.find (" ")).compare ("WindowHeight")) {
            tmp = tmp.substr (tmp.find_last_of (" ") + 1, tmp.length ());
            screen_height = atoi (tmp.c_str ());
        }
    }
}

的config.ini

[Display]
BitDepth = 32
WindowWidth = 853
WindowHeight = 480

1 个答案:

答案 0 :(得分:3)

您可以使用std::map使此方法更灵活。另请注意,不是检查config.eof()的erturn值,而是直接检查std::getline的返回值更好:

std::map<std::string, int> myConfig;

std::string line, key, delim;
while (std::getline(config, line))
{
    // skip empty lines:
    if (line.empty()) continue;

    // construct stream and extract tokens from it:
    std::string key, delim;
    int val;
    if (!(std::istringstream(line) >> key >> delim >> val) || delim != "=")
        break; // TODO: reading from the config failed 

    // store the new key-value config record:
    myConfig[key] = val;
}

当你解析其中一个配置行失败时,你应该如何处理这种情况:)