Monday, 11 January 2010

A good template function to cast string to numerical values

template bool from_string(T& t, const std::string& s, std::ios_base& (*f)(std::ios_base&))
{
std::istringstream iss(s);
return !(iss >> f >> t).fail();
}

usage:

float f;

from_string(f, std::string("123.456"), std::dec);

output:
f = 123.456

need to #include sstream

9 comments:

RING said...
This comment has been removed by a blog administrator.
好想好好休息 said...
This comment has been removed by a blog administrator.
下依個世紀 said...
This comment has been removed by a blog administrator.
佩璇 said...
This comment has been removed by a blog administrator.
柏辰 said...
This comment has been removed by a blog administrator.
韻玉 said...
This comment has been removed by a blog administrator.
RooseveltHouchi嬌琪 said...
This comment has been removed by a blog administrator.
靖福 said...
This comment has been removed by a blog administrator.
石JaquelynS_Whitesi白 said...
This comment has been removed by a blog administrator.