Given a single-digit string in C++, convert it into a corresponding boolean value, i.e., if the string is 1, the corresponding boolean value should be true, and if the string is 0, the corresponding boolean value should be false.

1. Using boost::lexical_cast function

The idea is to use the boost::lexical_cast for this, which has the major advantage: it throws a boost::bad_lexical_cast exception whenever it cannot construct a boolean value out of the given string.

Download Code

2. Using std::istringstream function

We can also use string streams for this, as shown below. It works fine but sets the boolean value to false on any invalid input.

Download  Run Code

3. Using equality operator

Finally, for a task as simple as this is, we can write our own validator using the equality operator, as shown below. But like the previous function, this also sets the boolean value to false on any invalid input.

Download  Run Code

That’s all about converting a string to bool value in C++.