Converting from a std::string to bool

109,242

Solution 1

It'll probably be overkill for you, but I'd use boost::lexical_cast

boost::lexical_cast<bool>("1") // returns true
boost::lexical_cast<bool>("0") // returns false

Solution 2

I am surprised that no one mentioned this one:

bool b;
istringstream("1") >> b;

or

bool b;
istringstream("true") >> std::boolalpha >> b;

Solution 3

bool to_bool(std::string const& s) {
     return s != "0";
}

Solution 4

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.

Solution 5

There is also std::stoi in c++11:

bool value = std::stoi(someString.c_str());

Share:
109,242
cquillen
Author by

cquillen

Updated on November 09, 2020

Comments

  • cquillen
    cquillen over 3 years

    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 boolean value.