How to parse a string to an int in C++?

前端 未结 17 1730
忘了有多久
忘了有多久 2020-11-21 11:01

What\'s the C++ way of parsing a string (given as char *) into an int? Robust and clear error handling is a plus (instead of returning zero).

17条回答
  •  悲&欢浪女
    2020-11-21 11:44

    From C++17 onwards you can use std::from_chars from the header as documented here.

    For example:

    #include 
    #include 
    #include 
    
    int main()
    {
        char const * str = "42";
        int value = 0;
    
        std::from_chars_result result = std::from_chars(std::begin(str), std::end(str), value);
    
        if(result.error == std::errc::invalid_argument)
        {
          std::cout << "Error, invalid format";
        }
        else if(result.error == std::errc::result_out_of_range)
        {
          std::cout << "Error, value too big for int range";
        }
        else
        {
          std::cout << "Success: " << result;
        }
    }
    

    As a bonus, it can also handle other bases, like hexadecimal.

提交回复
热议问题