To include the line number in error messages during parsing, we need to keep track of the current line number as we process the file. We can modify the ParseConfig()
method to do this and pass the line number to ProcessLine()
.
Here's how we can modify ParseConfig()
and ProcessLine()
to track and use the line number:
// config.txt
WINDOW_TITLE: My Game
INVALID_FORMAT
WINDOW_WIDTH: 800
INVALID_KEY: 123
#include <SDL.h>
#include <iostream>
#include <string>
#include <vector>
class Config {
public:
void ParseConfig(const std::string& Content) {
size_t Start{0};
size_t End{Content.find('\n', Start)};
int LineNumber{1};
while (End != std::string::npos) {
ProcessLine(Content.substr(
Start, End - Start), LineNumber);
Start = End + 1;
End = Content.find('\n', Start);
LineNumber++;
}
ProcessLine(
Content.substr(Start), LineNumber);
}
void ProcessLine(
const std::string& Line,
int LineNumber
) {
size_t Delim{Line.find(": ")};
if (Delim == std::string::npos) {
std::cout << "Error: Invalid format on "
"line " << LineNumber << "\n";
return;
}
std::string Key{Line.substr(0, Delim)};
std::string Value{Line.substr(Delim + 2)};
if (Key == "WINDOW_TITLE") {
WindowTitle = Value;
} else if (Key == "WINDOW_WIDTH") {
WindowWidth = std::stoi(Value);
} else if (Key == "WINDOW_HEIGHT") {
WindowHeight = std::stoi(Value);
} else if (Key == "LEVELS") {
ParseLevels(Value);
} else {
std::cout << "Error: Unknown key '"
<< Key << "' on line " << LineNumber
<< "\n";
}
}
};
int main() {
Config MyConfig;
MyConfig.Load("config.txt");
}
Error: Invalid format on line 2
Error: Unknown key 'INVALID_KEY' on line 4
LineNumber
in ParseConfig()
: We initialize LineNumber
to 1
and increment it each time we process a line.LineNumber
to ProcessLine()
: We pass the LineNumber
as an argument to ProcessLine()
.LineNumber
in Error Messages: In ProcessLine()
, we can now include the LineNumber
in any error messages we output.ParseLevels()
: You could add similar line number tracking to ParseLevels()
to provide more specific error locations if there are issues parsing the LEVELS
data.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