简体   繁体   中英

std::stoull but with string_view

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 ?

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.

No there isn't, and cppreference explains why:

stoull ... calls std::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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM