Safely convert std::string_view to int (like stoi or atoi)

后端 未结 2 698
粉色の甜心
粉色の甜心 2020-12-19 01:17

Is there a safe standard way to convert std::string_view to int?


Since C++11 std::string lets us use stoi

2条回答
  •  独厮守ぢ
    2020-12-19 01:41

    The std::from_chars function does not throw, it only returns a value of type from_chars_result which is basically a struct with two fields:

    struct from_chars_result {
        const char* ptr;
        std::errc ec;
    };
    

    You should inspect the values of ptr and ec when the function returns:

    #include 
    #include 
    #include 
    
    int main()
    {
        int i3;
        std::string_view sv = "abc";
        auto result = std::from_chars(sv.data(), sv.data() + sv.size(), i3);
        if (result.ec == std::errc::invalid_argument) {
            std::cout << "Could not convert.";
        }
    }
    

提交回复
热议问题