2011/05/10

c++で文字列から数値に変換

c++でstd::istringstreamを使用して文字列から数値に変換するプログラムです。
templateを使用しているので、様々な型で変換できます。


#include <iostream>
#include <string>
#include <iomanip> // setprecision
#include <sstream>

using namespace std;

//! 文字列から値に変換します。
template < typename T > T convert( const std::string & str )
{
 std::istringstream istream( str );
 T type = 0;

 if ( !str.empty())
 {
  istream >> type;
 }
 cout << type << endl;
 return type;
};

int main()
{
 unsigned long val = convert< unsigned long >( "12345678901" );
 cout << val << endl;

 long double tmp = convert< long double >( "123.45678" );
 cout << setprecision( 10 ) << tmp << endl;
 return 0;
}

28行目のcoutでsetprecisionで有効桁数を指定しないと、小数点4桁目(環境によります)が四捨五入されて表示されます。
(指定し忘れてて、はまりました。。)

0 コメント:

コメントを投稿

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Blogger Templates