How to convert a number to string and vice versa in C++

前端 未结 5 869
鱼传尺愫
鱼传尺愫 2020-11-22 03:36

Since this question gets asked about every week, this FAQ might help a lot of users.

  • How to convert an integer to a string in C++

  • how to con

5条回答
  •  逝去的感伤
    2020-11-22 04:04

    In C++17, new functions std::to_chars and std::from_chars are introduced in header charconv.

    std::to_chars is locale-independent, non-allocating, and non-throwing.

    Only a small subset of formatting policies used by other libraries (such as std::sprintf) is provided.

    From std::to_chars, same for std::from_chars.

    The guarantee that std::from_chars can recover every floating-point value formatted by to_chars exactly is only provided if both functions are from the same implementation

     // See en.cppreference.com for more information, including format control.
    #include 
    #include 
    #include 
    #include 
    #include 
    
    using Type =  /* Any fundamental type */ ;
    std::size_t buffer_size = /* ... */ ;
    
    [[noreturn]] void report_and_exit(int ret, const char *output) noexcept 
    {
        std::printf("%s\n", output);
        std::exit(ret);
    }
    void check(const std::errc &ec) noexcept
    {
        if (ec ==  std::errc::value_too_large)
            report_and_exit(1, "Failed");
    }
    int main() {
        char buffer[buffer_size];        
        Type val_to_be_converted, result_of_converted_back;
    
        auto result1 = std::to_chars(buffer, buffer + buffer_size,  val_to_be_converted);
        check(result1.ec);
        *result1.ptr = '\0';
    
        auto result2 = std::from_chars(buffer, result1.ptr, result_of_converted_back);
        check(result2.ec);
    
        assert(val_to_be_converted == result_of_converted_back);
        report_and_exit(0, buffer);
    }
    

    Although it's not fully implemented by compilers, it definitely will be implemented.

提交回复
热议问题