lexical_cast
Boostの中ではとても簡単なlexical_cast
stringstreamをラップしてるだけだもんね。
#include <exception> #include <sstream> #include <string> namespace shand { class bad_lexical_cast : public std::bad_cast { public: bad_lexical_cast(const std::string& what) : std::bad_cast(what.c_str()) {} }; template <class AfterType, class BeforeType> AfterType lexical_cast(const BeforeType& target) { AfterType result; std::stringstream interpreter; if (!(interpreter << target && interpreter >> result)) throw bad_lexical_cast("bad_lexical_cast"); return result; } template <class AfterType, class BeforeType> AfterType wlexical_cast(const BeforeType& target) { AfterType result; std::wstringstream interpreter; if (!(interpreter << target && interpreter >> result)) throw bad_lexical_cast("bad_lexical_cast"); return result; } } // namespace shand
サンプル
#include <iostream> #include <string> #include <shand/lexical_cast.hpp> using namespace std; using namespace shand; int main() { // 1.文字列から整数へ変換 int value = lexical_cast<int>("123"); // 2.整数から文字列へ変換 string str = lexical_cast<string>(123); // 3.文字列から実数へ変換 double pi = lexical_cast<double>(3.14); // 4.ワイド文字版 wstring wstr = wlexical_cast<wstring>(314); // 変換失敗時のための例外処理 try { lexical_cast<int>("abc"); } catch (bad_lexical_cast& ex) { cout << ex.what() << endl; throw; } return 0; }
でも、あんまり実用しないので↓これで十分かと
to_string / to_wstring
template <class Type> std::string to_string(const Type& target) { std::stringstream interpreter; interpreter << target; return interpreter.str(); } template <class Type> std::wstring to_wstring(const Type& target) { std::wstringstream interpreter; interpreter << target; return interpreter.str(); }
サンプル
#include <string> #include <shand/string_algorthm.h> using namespace std; using namespace shand; int main() { string str = to_string(3); string pi = to_string(3.14); wstring wstr = to_wstring(5); return 0; }