Reputation: 740
Is there a std::stoull
which takes a basic_string_view
? I don't want to construct a string just to call std::stoull
, especially since it takes it by const &
.
If none exists, what is an efficient way to convert a std::basic_string_view
to unsigned long long
?
Upvotes: 2
Views: 2897
Reputation: 61920
If you're looking for more efficiency, C++17 introduced lower-level conversions in <charconv>
(live example):
#include <charconv>
#include <iostream>
#include <string_view>
using namespace std::literals;
int main() {
const auto str = "2048"sv;
unsigned long long result;
auto [ptr, err] = std::from_chars(str.data(), str.data() + str.size(), result);
if (err == std::errc{} && ptr == str.data() + str.size()) {
std::cout << "Entire conversion successful: " << result;
}
}
The reason I don't use str.begin()
and str.end()
is because the API works directly on const char*
, not iterators.
Upvotes: 7
Reputation: 25388
No there isn't, and cppreference explains why:
stoull
... callsstd::strtoull(str.c_str(), &ptr, base)
which requires a nul-terminated string (which std::string_view
does not promise to provide).
Note, however, that std::string
has a converting constructor that takes a string_view
so you can write:
auto ull = std::stoull (std::string (my_string_view));
which is probably as good a solution as any.
Upvotes: 1