C++のstringとintの相互変換

よく調べてしまうのでメモしとく。

#include <string>
#include <sstream>

using namespace std;

//conversion
//------------------------------------------
inline int toInt(std::string s) {int v; std::istringstream sin(s);sin>>v;return v;}
template<class T> inline std::string toString(T x) {std::ostringstream sout;sout<<x;return sout.str();}

includeするライブラリはstringとsstreamの二つ。

使い方は

string foo = "123";
cout << toInt(foo) << endl;

int bar = 123;
cout << toString<int>(bar) << endl;
double hoge = 123.456;
cout << toString<double>(hoge) << endl;

という風になる。

実行用のソースコードこちら↓

追記2013/11/18
コピペするとき面倒なので"std::"をつけた。

(追記 2012/11/4)

inline int toInt を using namespace std; の後に置かないとこんなエラーが出そう。

qr_19040aRD.cpp:8:18: エラー: ‘toInt’ declared as an ‘inline’ variable
qr_19040aRD.cpp:8:18: エラー: ‘string’ was not declared in this scope