Trimming Extra Spaces

What if a key in our config file has multiple spaces before or after it, such as " KEY : VALUE"? How can we trim leading/trailing spaces from the key and value?

If a key or value in our configuration file has extra spaces at the beginning (leading) or end (trailing), we need a way to remove them. This process is often called "trimming".

Implementing Trim()

We can create a helper function called Trim() that takes a std::string and returns a new std::string with the leading and trailing spaces removed.

#include <iostream>
#include <string>

std::string Trim(const std::string& Str) {
  size_t First{Str.find_first_not_of(' ')};
  if (First == std::string::npos) {
    return Str;
  }

  size_t Last{Str.find_last_not_of(' ')};

  return Str.substr(First, (Last - First + 1));
}

int main() {
  std::string Test{"   WINDOW_WIDTH   "};
  std::cout << "|" << Trim(Test) << "|";
}
|WINDOW_WIDTH|

Using Trim() in ProcessLine()

Now, let's see how we can use our Trim() function within the ProcessLine() function of our Config class:

#include <iostream>
#include <string>

std::string Trim(const std::string& Str) {
  // The following code is the same as the
  // previous example
  size_t First{Str.find_first_not_of(' ')};
  if (First == std::string::npos) {
    return Str;
  }

  size_t Last{Str.find_last_not_of(' ')};

  return Str.substr(First, (Last - First + 1));
}

class Config {/*...*/}; int main() { Config C; C.ProcessLine(" WINDOW_WIDTH : 800 "); }
Key: |WINDOW_WIDTH|
Value: |800|

Here we apply Trim() to both the Key and Value strings after we've extracted them from the line. This ensures that any leading or trailing spaces are removed before we process or store the values.

Parsing Data using std::string

Learn how to read, parse, and use config files in your game using std::string and SDL_RWops

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Moving Past Delimiters
Why do we use Start = End + 1 to move to the next position after finding a delimiter (like \n or ,)?
Config from Network Stream
What changes would be needed to load the config from a different source, like a network stream, instead of a file?
Saving Config Changes
How could we extend the Config class to allow writing the configuration back to a file, effectively saving changes made in-game?
Implementing a Default Config
How could we implement a default configuration that is used if the config file is missing or invalid?
Error Line Numbers
When we encounter an error parsing a file, how can we output an error message that includes where the error occurred - for example, the line number within the file?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant