Converting from a std::string to bool

前端 未结 14 2643
走了就别回头了
走了就别回头了 2020-12-25 09:51

What is the best way to convert a std::string to bool? I am calling a function that returns either \"0\" or \"1\", and I need a clean solution for turning this into a boole

14条回答
  •  旧时难觅i
    2020-12-25 10:22

    Either you care about the possibility of an invalid return value or you don't. Most answers so far are in the middle ground, catching some strings besides "0" and "1", perhaps rationalizing about how they should be converted, perhaps throwing an exception. Invalid input cannot produce valid output, and you shouldn't try to accept it.

    If you don't care about invalid returns, use s[0] == '1'. It's super simple and obvious. If you must justify its tolerance to someone, say it converts invalid input to false, and the empty string is likely to be a single \0 in your STL implementation so it's reasonably stable. s == "1" is also good, but s != "0" seems obtuse to me and makes invalid => true.

    If you do care about errors (and likely should), use

    if ( s.size() != 1
     || s[0] < '0' || s[0] > '1' ) throw input_exception();
    b = ( s[0] == '1' );
    

    This catches ALL errors, it's also bluntly obvious and simple to anyone who knows a smidgen of C, and nothing will perform any faster.

提交回复
热议问题