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

后端 未结 2 708
粉色の甜心
粉色の甜心 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:36

    Unfortunately, there is no standard way that would throw an exception for you but std::from_chars has a return value code that you may use:

    #include 
    #include 
    
    template 
    void from_chars_throws(const char* first, const char* last, T &t, Args... args) {
        std::from_chars_result res = std::from_chars(first, last, t, args... );
    
        // These two exceptions reflect the behavior of std::stoi.
        if (res.ec == std::errc::invalid_argument) {
            throw std::invalid_argument{"invalid_argument"};
        }
        else if (res.ec == std::errc::result_out_of_range) {
            throw std::out_of_range{"out_of_range"};
        }
    }
    
    

    Obviously you can create svtoi, svtol from this, but the advantage of "extending" from_chars is that you only need a single templated function.

提交回复
热议问题