0

有没有更好的方法让我从文件中读取值并相应地设置它们?我可以以某种方式从文件中读取变量名并在程序中相应地设置它吗?例如,读取 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 ());
        }
    }
}

配置文件

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

1 回答 1

3

您可以使用std::map使这种方法更加灵活。另请注意,与其检查 erturn 的值,config.eof()不如直接检查以下的返回值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;
}

当配置行之一的解析失败时,您将如何处理这种情况取决于您:)

于 2013-03-18T11:14:51.240 回答