Reputation: 173
Is there a better way for me to read values from a file and set them accordingly? Could I somehow read a variable name from the file and set it accordingly in the program? For example, read BitDepth and set it to the value stated in the file? Therefore, I don't have to check if this line is BitDepth then set bit_depth to that value that follows?
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
Upvotes: 0
Views: 119
Reputation: 42133
You could use std::map
to make this approach more flexible. Also note that instead of checking the erturn value of config.eof()
it is much better to check the return value of std::getline
directly:
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;
}
It's up to you how you deal with the situation when the parsing of one of the config lines fails :)
Upvotes: 3