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
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.