The last lesson's edit returned only an Error, because a successful edit has nothing to hand back. A parser is different. When it succeeds it produces a task, and when it fails the caller wants to know why: was the line the wrong shape (missing separators, extra fields), or did it have the right shape with a bad value in a field? An std::optional<Task> carries the task but loses the reason, and an Error carries the reason but loses the task.
A result record carries both: a struct with an optional value and an error code. The tracker's parser returns struct ParseResult { std::optional<Task> task; Error error; };. It labels a wrong field structure as malformed and a bad field value as invalid, and only a fully accepted line produces a task.
Predict and run
parse_positive rejects values of zero or less. What are the two numbers on the line?
#include <iostream>
#include <optional>
enum class Error { none, invalid };
struct Result { std::optional<int> value; Error error; };
Result parse_positive(int input) {
if (input <= 0) { return {std::nullopt, Error::invalid}; }
return {input, Error::none};
}
int main() {
Result result = parse_positive(-1);
std::cout << result.value.has_value() << " " << (result.error == Error::invalid) << "\n";
return 0;
}Check your prediction
0 1The rejected input produces an empty value and the error invalid. The braces in return {std::nullopt, Error::invalid}; initialize the two members in declaration order. Try parse_positive(5): the line becomes 1 0, a present value and no error.
A convention with two legal states
Two members with two possibilities each give four combinations, and only two are meaningful:
- Value present,
Error::none: success. - Value empty, a real error: failure, with the reason.
- Value present, a real error: contradictory. Should the caller use the value or not?
- Value empty,
Error::none: also contradictory. It failed, but for no reason?
Nothing in the struct prevents the last two; it is a convention that every function returning a Result must keep and every test must check. You can make the convention much harder to break by never writing the braces by hand. Two small helper functions build the only legal combinations:
#include <iostream>
#include <optional>
enum class Error { none, malformed, invalid };
struct Result { std::optional<int> value; Error error; };
Result ok(int value) { return {value, Error::none}; }
Result fail(Error error) { return {std::nullopt, error}; }
Result parse_digit(char ch) {
if (ch == ' ') { return fail(Error::malformed); }
if (ch < '0' || ch > '9') { return fail(Error::invalid); }
return ok(ch - '0');
}
int main() {
for (char ch : {'7', 'x', ' '}) {
Result result = parse_digit(ch);
if (result.value) {
std::cout << "'" << ch << "' -> " << *result.value << "\n";
} else {
std::cout << "'" << ch << "' -> error " << static_cast<int>(result.error) << "\n";
}
}
return 0;
}'7' -> 7
'x' -> error 2
' ' -> error 1A caller should test the value first and read the error only when it is empty. Printing the error as a number is fine for a quick experiment; a real program maps it to a message as the last lesson did.
Newer C++ has types that make the contradictory states impossible to represent. C++23's std::expected<T, E> holds either a value or an error, never both. It is a later topic; a two-member struct with helper functions is enough for this project, as long as the tests check both sides.
Malformed versus invalid
The tracker's line format is id|minutes|state|title. The parser decides the two kinds of failure at different stages:
- Malformed: the structure is wrong before any field is read. There are fewer than three
|separators, or more than three. - Invalid: the structure is right but a field fails its rule. The ID has a letter in it, the minutes are 0, the state is
later, or the title is empty.
Splitting the stages this way keeps each check small. The structural check only counts separators, and each field check can assume it received exactly one field. The distinction also helps a user fix a file: "malformed" suggests a missing |, "invalid" suggests a bad number or word.
Practice
Your turn
Write Result parse_entry(const std::string& line) for lines of the form minutes|state. A line without exactly one | is malformed. Minutes must be one to three digits with a value of 1 through 180, and the state must be todo or done, otherwise invalid. On success, return an Entry with the minutes and a done flag. Print:
25|todo -> 25 minutes, todo
180|done -> 180 minutes, done
25todo -> malformed
25|todo|x -> malformed
0|todo -> invalid
25|later -> invalid
x5|done -> invalid#include <iostream>
#include <optional>
#include <string>
enum class Error { none, malformed, invalid };
struct Entry { int minutes; bool done; };
struct Result { std::optional<Entry> entry; Error error; };
// Write ok, fail and parse_entry here.
int main() {
return 0;
}Hint 1: the idea
Decide the shape before the values. Find the separator first; only when there is exactly one do you split the line and check each field.
Hint 2: a first step
auto bar = line.find('|'); gives the first separator or std::string::npos. A second separator exists if line.find('|', bar + 1) != std::string::npos. Then line.substr(0, bar) is the minutes text and line.substr(bar + 1) is the state.
Show one solution
#include <iostream>
#include <optional>
#include <string>
enum class Error { none, malformed, invalid };
struct Entry { int minutes; bool done; };
struct Result { std::optional<Entry> entry; Error error; };
Result ok(Entry entry) { return {entry, Error::none}; }
Result fail(Error error) { return {std::nullopt, error}; }
std::optional<int> minutes_field(const std::string& text) {
if (text.empty() || text.size() > 3) { return std::nullopt; }
int value = 0;
for (char ch : text) {
if (ch < '0' || ch > '9') { return std::nullopt; }
value = value * 10 + (ch - '0');
}
if (value < 1 || value > 180) { return std::nullopt; }
return value;
}
Result parse_entry(const std::string& line) {
const auto bar = line.find('|');
if (bar == std::string::npos || line.find('|', bar + 1) != std::string::npos) {
return fail(Error::malformed);
}
const auto minutes = minutes_field(line.substr(0, bar));
const std::string state = line.substr(bar + 1);
if (!minutes || (state != "todo" && state != "done")) { return fail(Error::invalid); }
return ok({*minutes, state == "done"});
}
int main() {
for (const std::string line : {"25|todo", "180|done", "25todo", "25|todo|x", "0|todo", "25|later", "x5|done"}) {
const Result result = parse_entry(line);
std::cout << line << " -> ";
if (result.entry) {
std::cout << result.entry->minutes << " minutes, " << (result.entry->done ? "done" : "todo") << "\n";
} else {
std::cout << (result.error == Error::malformed ? "malformed" : "invalid") << "\n";
}
}
return 0;
}25|todo -> 25 minutes, todo
180|done -> 180 minutes, done
25todo -> malformed
25|todo|x -> malformed
0|todo -> invalid
25|later -> invalid
x5|done -> invalidEvery return goes through ok or fail, so the function cannot produce a contradictory result. The separator count is checked before any field, which is why 25|todo|x is malformed rather than an invalid state todo|x. The project's parse_task has the same two stages for four fields. The next lesson uses validation results to protect edits that change several fields at once.
Completion is saved in this browser only. It does not measure mastery.