LoginSignup
3
5

More than 5 years have passed since last update.

[C++11~] 数値を文字列(std::string)に変換する

Last updated at Posted at 2017-03-24

数値を文字列に変換する際は、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

3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5