c++ - num_get facet and stringstream conversion to boolean - fails with initialised boolean? -
i have inherited template convert string numerical value, , want apply convert boolean. not experienced stringstream , locale classes. seem getting odd behaviour, , wondering if please explain me?
template<typename t> t convertfromstring( const string& str ) const { std::stringstream sstream( str ); t num = 0; sstream >> num; return num; }
this works fine until try boolean conversion
string str1("1"); int val1 = convertfromstring<int>(str1); // ok string str2("true"); bool val2 = convertfromstring<bool>(str2); // val2 _false_
i spent time tracking down problem. have confirmed locale's truename() returns "true".
the problem seems initialisation of variable num. can change template , works:
template<typename t> t convertfromstring( const string& str ) const { std::stringstream sstream( str ); t num; // <----------------------- changed here sstream >> num; return num; } string str2("true"); bool val2 = convertfromstring<bool>(str2); // val2 _true_
why work? accept initialising bool '0' wrong, why cause sstream>>num
conversion fail?
initialising bool 0 reliably set false, , has no effect on stream extraction.
what causing problem streams default recognize values 0
, 1
when dealing booleans. have them recognize names true
, false
, need tell explicitly stream boolalpha
manipulator.
the best way solve problems specialize template bool:
template<> bool convertfromstring<bool>( const string& str ) const { std::stringstream sstream( str ); bool val = false; sstream >> val; if( sstream.fail() ) { sstream.clear(); sstream >> boolalpha >> val; } return val; }
note change did not make code work. appeared single testcase used. change, function failed read stream , returned uninitialised value. non-zero value interpreted true, function appears work, try extract "false"
, see fail (the function still returns true).
edit: adapted code handle both numeric , alpha bools.
Comments
Post a Comment