Step 5 of 7
Passing errors up
Real programs are layers: main calls load_config, which calls parse_line, which calls parse_int. When the bottom layer fails, each layer above has two honest choices:
- Handle it: use a default, retry, skip the item, tell the user.
- Pass it up unchanged, usually with an early
return.
The one dishonest choice is swallowing it: returning a made-up value as if nothing went wrong. That's how bugs travel far from where they started.
#include <iostream>
#include <optional>
#include <string_view>
std::optional<int> digit(char c) {
if (c < '0' || c > '9') return std::nullopt;
return c - '0';
}
// Sum of the digits in a code like "4-7-1". Any bad character fails the whole thing.
std::optional<int> checksum(std::string_view code) {
int total = 0;
for (std::size_t i = 0; i < code.size(); i += 2) {
auto d = digit(code[i]);
if (!d) return std::nullopt; // pass the failure up
total += *d;
if (i + 1 < code.size() && code[i + 1] != '-') return std::nullopt;
}
return total;
}
int main() {
for (std::string_view c : {"4-7-1", "4-x-1", "9"}) {
auto sum = checksum(c);
if (sum) std::cout << c << " -> " << *sum << "\n";
else std::cout << c << " -> invalid\n"; // main handles it: tell the user
}
}
4-7-1 -> 12
4-x-1 -> invalid
9 -> 9
Reading the layers
digitknows what failed but not what to do about it, so it just reports.checksumcan't produce a meaningful sum from a bad digit, so it passes the failure up withreturn std::nullopt;as soon as it sees one.mainis where a decision can be made: it tells the user.
Your task: summing comma-separated values
Split the view at each comma. A loop with find(',') works well:
while (true) {
auto comma = s.find(',');
std::string_view part = s.substr(0, comma); // up to the comma, or everything
// ... parse part, pass failure up ...
if (comma == std::string_view::npos) break;
s.remove_prefix(comma + 1);
}
An empty part (as in "3,,4" or "") fails in parse_int, which is correct: pass it up.
Your turn: parse_int is written for you. Write std::optional<int> sum_csv(std::string_view s) that sums comma-separated integers like "3,4,-2". If any part fails to parse, the whole sum fails.