C++11標準ライブラリに新しく追加されたstd::to_string
関数についてメモ*1。
組み込み数値型(int
やdouble
)から文字列クラス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 callingsprintf(buf, fmt, val)
with a format specifier of "%d", "%u", "%ld", "%lu", "%lld", "%llu", "%f", "%f", or "%Lf", respectively, wherebuf
designates an internal character buffer of sufficient size.
関連URL
- http://d.hatena.ne.jp/nagoya313/20110214/1297690937/
- イグトランスの頭の中(のかけら) » std::to_stringはlocale指定の影響を受けるのか、またどういう書式なのか気になった
*1:ワイド文字列版の std::to_wstring も存在する。
*2:余談:float, double の両者に対応する書式指定文字列はともに "%f" であることに注意。理由は [迷信] double の出力書式は”%lf” あたりを参照。