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 ());
        }
    }
}

config.ini

[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;
}

構成行の 1 つの解析が失敗した場合の状況にどのように対処するかは、あなた次第です :)

于 2013-03-18T11:14:51.240 に答える