Implementing a Default Config
How could we implement a default configuration that is used if the config file is missing or invalid?
To use a default configuration when the config file is missing or invalid, we can add a method to our Config
class to set default values and modify the Load()
method to use these defaults if the file can't be loaded.
Setting Default Values
First, let's add a SetDefaults()
method to our Config
class:
#include <SDL.h>
#include <iostream>
#include <string>
#include <vector>
class Config {
public:
std::string WindowTitle;
int WindowWidth;
int WindowHeight;
std::vector<int> Levels;
void SetDefaults() {
WindowTitle = "Default Window Title";
WindowWidth = 800;
WindowHeight = 600;
Levels = {1, 2, 3};
}
};
int main() {
Config MyConfig;
MyConfig.Load("missing.txt");
std::cout << MyConfig.WindowTitle << "\n";
std::cout << MyConfig.WindowWidth << "\n";
std::cout << MyConfig.WindowHeight << "\n";
}
Failed to open config file: Couldn't open missing.txt
Default Window Title
800
600
Modifying Load()
Now, we modify the Load()
method to call SetDefaults()
if ReadFile()
returns an empty string (indicating the file was missing or couldn't be read):
void Load(const std::string& Path) {
std::string Content{ReadFile(Path)};
if (Content.empty()) {
// Use default values if the file
// is not found or invalid
SetDefaults();
return;
}
ParseConfig(Content);
}
Explanation
SetDefaults()
: This method assigns sensible default values to each member of theConfig
class. You can customize these defaults to whatever makes sense for your game.Load()
Modification: In theLoad()
method, we check ifContent
is empty after callingReadFile()
. If it is, we callSetDefaults()
to initialize theConfig
object with the default values.
Usage
Now, if you try to load a config file that doesn't exist or is invalid, your Config object will be populated with the default values. This ensures your game can still start with reasonable settings even if the configuration file is missing.
Parsing Data using std::string
Learn how to read, parse, and use config files in your game using std::string
and SDL_RWops