Parse lines like "port = 8080" with std::string_view (trimming spaces, skipping # comments) into a map, and write get_int(key) returning std::optional<int>.
#include <charconv>
#include <iostream>
#include <map>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
std::string_view trim(std::string_view s) {
auto b = s.find_first_not_of(' ');
if (b == std::string_view::npos) return {};
return s.substr(b, s.find_last_not_of(' ') - b + 1);
}
class Config {
std::map<std::string, std::string, std::less<>> values_;
public:
void parse(std::string_view line) {
line = trim(line);
if (line.empty() || line.starts_with('#')) return;
if (auto eq = line.find('='); eq != std::string_view::npos)
values_.emplace(trim(line.substr(0, eq)), trim(line.substr(eq + 1)));
}
std::optional<int> get_int(std::string_view key) const {
auto it = values_.find(key); // heterogeneous lookup: no std::string built
if (it == values_.end()) return std::nullopt;
int v{};
auto [p, ec] = std::from_chars(it->second.data(), it->second.data() + it->second.size(), v);
if (ec != std::errc{} || p != it->second.data() + it->second.size()) return std::nullopt;
return v;
}
std::size_t size() const { return values_.size(); }
};
int main() {
std::vector<std::string> lines{"# server settings", "host = example.local", " port = 8080 ", "workers=4", "timeout = 30s", ""};
Config cfg;
for (const auto& l : lines) cfg.parse(l);
for (std::string_view key : {"port", "workers", "timeout", "retries"})
std::cout << key << ": " << (cfg.get_int(key) ? std::to_string(*cfg.get_int(key)) : "n/a") << '\n';
std::cout << cfg.size() << " keys\n";
return 0;
}
port: 8080 workers: 4 timeout: n/a retries: n/a 4 keys
string_view slices lines without copying; std::less<> enables lookups by string_view; optional distinguishes "missing or invalid" from a real 0.