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.
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
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);
}
SetDefaults()
: This method assigns sensible default values to each member of the Config
class. You can customize these defaults to whatever makes sense for your game.Load()
Modification: In the Load()
method, we check if Content
is empty after calling ReadFile()
. If it is, we call SetDefaults()
to initialize the Config
object with the default values.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.
Answers to questions are automatically generated and may not have been reviewed.
std::string
Learn how to read, parse, and use config files in your game using std::string
and SDL_RWops