Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting from a std::string to bool

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.

like image 593
cquillen Avatar asked Jan 29 '10 23:01

cquillen


People also ask

Can you convert a string to a bool in C++?

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. That's all about converting a string to bool value in C++.

How do you change a string from true to boolean true?

To convert String to Boolean, use the parseBoolean() method in Java. The parseBoolean() parses the string argument as a boolean. The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".

How do I convert a string to a number in C++?

One effective way to convert a string object into a numeral int is to use the stoi() function. This method is commonly used for newer versions of C++, with is being introduced with C++11. It takes as input a string value and returns as output the integer version of it.

Is std :: string the same as string?

There is no functionality difference between string and std::string because they're the same type.


1 Answers

I am surprised that no one mentioned this one:

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

or

bool b; istringstream("true") >> std::boolalpha >> b; 
like image 160
David L. Avatar answered Oct 12 '22 00:10

David L.