To extract data from a parsed TOML file, use toml::Result in combination with get() or seek() methods on the retrieved Datum objects.
get() method
Use result.get({"key1", "key2"}) to retrieve a value using a list of keys representing the path to the nested element. This returns a pointer to a Datum.
seek() method
Use result.seek("key1.key2") to retrieve a value using a dot-separated string path. This also returns a pointer to a Datum.
Error Handling
Both methods return std::optional wrappers (via methods like .as_str() or .as_intvec()). If the key does not exist or the type is incorrect, calling .value() on the optional will throw std::bad_optional_access. It is recommended to wrap these calls in try-catch blocks.
Example
// Parse the file
toml::Result result = toml::parse_file_ex("simple.toml");
if (!result.ok()) {
// Handle parse error using result.errmsg()
}
try {
// Accessing nested string via get()
std::string host = result.get({"server", "host"})->as_str().value();
// Accessing nested array via seek()
std::vector<int64_t> ports = result.seek("server.port")->as_intvec().value();
} catch (const std::bad_optional_access &ex) {
// Handle missing or invalid properties
}
/*
* Parse the config file simple.toml:
*
* [server]
* host = "www.example.com"
* port = [8080, 8181, 8282]
*
*/
#include "../src/tomlcpp.hpp"
#include <iostream>
#include <vector>
using std::cout;
static void error(const char *msg) {
fprintf(stderr, "ERROR: %s\n", msg);
exit(1);
}
int main() {
// Parse the toml file
toml::Result result = toml::parse_file_ex("simple.toml");
// Check for parse error
if (!result.ok()) {
error(result.errmsg());
}
// Extract values
std::string host;
std::vector<int64_t> port;
try {
// use the Datum::get() method
host = result.get({"server", "host"})->as_str().value();
} catch (const std::bad_optional_access &ex) {
error("missing or invalid 'server.host' property in config");
}
try {
// use the Datum::seek() method
port = result.seek("server.port")->as_intvec().value();
} catch (const std::bad_optional_access &ex) {
error("missing or invalid 'server.port' property in config");
}
// Print values
cout << "server.host = " << host << "\n";
cout << "server.port = [";
for (size_t i = 0; i < port.size(); i++) {
cout << (i ? ", " : "") << port[i];
}
cout << "]\n";
// Done! No need to call toml_free(). Result::~Result() will handle destruction.
return 0;
}