Parsing Data using std::string

Implementing a Default Config

How could we implement a default configuration that is used if the config file is missing or invalid?

Abstract art representing computer programming

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

  1. 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.
  2. 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.

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.

Answers to questions are automatically generated and may not have been reviewed.

sdl2-promo.jpg
Part of the course:

Game Dev with SDL2

Learn C++ and SDL development by creating hands on, practical projects inspired by classic retro games

Free, unlimited access

This course includes:

  • 79 Lessons
  • 100+ Code Samples
  • 91% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2025 - All Rights Reserved