yohhoyの日記

技術的メモをしていきたい日記

to_string関数

C++11標準ライブラリに新しく追加されたstd::to_string関数についてメモ*1

組み込み数値型(intdouble)から文字列クラスstd::stringに変換する。変換処理はsprintf相当で行われる(書式指定文字列については後述)。

#include <string>

auto s1 = std::to_string(42);
assert(s1 == "42");
auto s2 = std::to_string(3.14);
assert(s2 == "3.14");

Boost.Lexical_Castライブラリでも代替可能。

#include <boost/lexical_cast.hpp>

auto s1 = boost::lexical_cast<std::string>(42);
assert(s1 == "42");
auto s2 = boost::lexical_cast<std::string>(3.14);
assert(s2 == "3.14");

N3337 21.5/p7より引用。引数の型Tはint, unsigned, long, unsigned long, long long, unsigned long long, float, double, long doubleのオーバーロードが定義される*2

string to_string(T val);

Returns: Each function returns a string object holding the character representation of the value of its argument that would be generated by calling sprintf(buf, fmt, val) with a format specifier of "%d", "%u", "%ld", "%lu", "%lld", "%llu", "%f", "%f", or "%Lf", respectively, where buf designates an internal character buffer of sufficient size.

関連URL

*1:ワイド文字列版の std::to_wstring も存在する。

*2:余談:float, double の両者に対応する書式指定文字列はともに "%f" であることに注意。理由は [迷信] double の出力書式は”%lf” あたりを参照。