C++標準での文字列<=>数値変換
boost::lexical_cast と同等の処理をC++標準で実現する。
ただしエラーは考慮しない。
・ジェネリック版
#include <sstream>
template <typename T>
T LexicalCast(char const* src) {
std::istringstream is(src); T x; is >> x; return x;
}
template <typename T>
T LexicalCast(std::string const& src) {
return LexicalCast<T>(src.c_str());
}
template <typename T, typename U>
T LexicalCast(U src) {
std::ostringstream os; os << src; return os.str();
}
#define INT(a) LexicalCast<int>(a)
#define STR(a) LexicalCast<std::string>(a)
・省コード版
#include <sstream>
int INT(std::string src) { std::istringstream is(src); int x; is >> x; return x; }
template <typename T>
std::string STR(T src) { std::ostringstream os; os << src; return os.str(); }
・使用例
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
cout << INT("01234") << endl; // 1234
string s = STR(56789);
reverse(s.begin(), s.end());
cout << s << endl; // 98765
cout << INT(s) + 1 << endl; // 98766
cout << STR(0)[0] << STR(9)[0] << endl; // 09
return 0;
}
0 件のコメント:
コメントを投稿