我有更好的方法从文件读取值并相应地设置它们吗?我可以以某种方式从文件中读取变量名称并在程序中相应地设置它吗?例如,读取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
答案 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;
}
当你解析其中一个配置行失败时,你应该如何处理这种情况:)