If you are on C++17, you can use std::from_chars to convert your string into numerical values. It is much faster than boost::lexical_cast.
A sample usage can be:
int parsed_num{};
std::string to_parse{"123"};
std::from_chars(to_parse.begin(), to_parse.end(), parsed_num);
The function returns a struct with the error code and a pointer to the rest of the unparsed string. If the usage seems a little involved, you can always wrap it in a templated wrapper function that can define the variable for you, pass it to from_chars, and then return the result. One implementation can be:
#include <charconv>
#include <string_view>
#include <stdexcept>
#include <optional>
template<typename T, typename SAFE_PARSE_T=unsafe_parse>
[[nodiscard]] inline constexpr T parse(std::string_view sv,
const std::optional<T> default_val={},
const char** next = nullptr)
noexcept(SAFE_PARSE_T::value)
{
if constexpr(not SAFE_PARSE_T::value) {
sv.remove_prefix(sv.find_first_not_of("+ "));
}
T var {default_val.value_or(T{})};
auto ec = std::from_chars(sv.cbegin(), sv.cend(), var);
if (next) *next = ec.ptr;
if constexpr(not SAFE_PARSE_T::value) {
if (default_val) {
return var;
}
if(ec.ec!=std::errc{}) {
throw std::runtime_error{"Parsing error!"};
}
}
return var;
}
source: https://thecodepad.com/cpp/performant-string-parsing-in-cpp/