From 012d44d958a8736c293c7eaf74dd3740f2d05039 Mon Sep 17 00:00:00 2001 From: Jie Date: Fri, 3 Jan 2025 18:17:59 +0800 Subject: [PATCH] add number to std::string funtion --- include/toolkit.h | 23 +++++++++++++++++++++++ src/main.cpp | 6 ++++-- 2 files changed, 27 insertions(+), 2 deletions(-) create mode 100644 include/toolkit.h diff --git a/include/toolkit.h b/include/toolkit.h new file mode 100644 index 0000000..9f34ae6 --- /dev/null +++ b/include/toolkit.h @@ -0,0 +1,23 @@ +#ifndef TOOLKIT_H +#define TOOLKIT_H + +#include +#include + +//use for to_chars +constexpr size_t buffer_size = 32; + +namespace toolkit{ + //number to std::string; + template + std::expected itos(T value){ + char buffer[buffer_size]; + auto res = std::to_chars(buffer, buffer+buffer_size, value); + if(res.ec != std::errc()){ + return std::unexpected(std::make_error_code(res.ec).message()); + } + return std::string(buffer, res.ptr - buffer); + } +} + +#endif diff --git a/src/main.cpp b/src/main.cpp index 7c435d2..05f7712 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,9 +1,11 @@ #include - +#include using namespace std; int main(int argc, char** argv) { - cout << "hello world!" << endl; + double num = .2; + auto str = toolkit::itos(num); + cout<