Convert a string to bool value in C++
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <boost/lexical_cast.hpp> #include <string> int main() { std::string s = "1"; bool b; try { b = boost::lexical_cast<bool>(s); std::cout << std::boolalpha << b << std::endl; } catch (boost::bad_lexical_cast const &e) // bad input { std::cout << "error" << std::endl; } return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <string> #include <sstream> int main() { std::string s = "1"; bool b; // returns false on bad input std::istringstream(s) >> b; std::cout << std::boolalpha << b << std::endl; return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> #include <string> int main() { std::string s = "1"; // returns false on bad input bool b = (s == "1"); std::cout << std::boolalpha << b << std::endl; return 0; } |
That’s all about converting a string to bool value in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)