数値を文字列に変換する際は、std::stringstream
だったり、Cのitoa
だったりを使用していましたが、
C++11からstd::to_string
を使えばもっと便利に変換できます。
std::to_string - cppreference.com
使用例
to_stringの使用例
#include <iostream>
#include <string>
#include <typeinfo>
#include <memory>
#include <cassert>
#include <cxxabi.h>
template<typename T>
void func(T message) {
auto demangle = [](const char* type_name) {
int status = -1;
std::unique_ptr<char, decltype(&std::free)> realname {
abi::__cxa_demangle(type_name, 0, 0, &status),
std::free
};
assert(status == 0);
return std::string(realname.get());
};
std::cout
<< demangle(typeid(message).name())
<< " : "
<< std::to_string(message)
<< std::endl;
}
int main(void) {
int _int = 123456;
long _long = 123456;
long long _longlong = 123456;
unsigned int _uint = 123456;
unsigned long _ulong = 123456;
unsigned long long _ulonglong = 123456;
float _float = 123.456;
double _double = 123.456;
long double _longdouble = 123.456;
func(_int);
func(_long);
func(_longlong);
func(_uint);
func(_ulong);
func(_ulonglong);
func(_float);
func(_double);
func(_longdouble);
}
実行結果
$ g++ -std=c++11 test.cpp && ./a.out
int : 123456
long : 123456
long long : 123456
unsigned int : 123456
unsigned long : 123456
unsigned long long : 123456
float : 123.456001
double : 123.456000
long double : 123.456000
参考
std::to_string - cppreference.com
Easiest way to convert int to string in C++ - Stack Overflow
本の虫: gccの名前のデマングル
c++ - std::unique_ptr for C functions that need free - Stack Overflow