Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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

koara-local
言語は最近は C#, Javaあたりがメイン。端末VimからIDEに移行。IntelliJすごい。Qiitaでの記事やその中の主張は、所属している企業/団体の意見を代表するものではありません。
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away