Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ std::string to boolean

Tags:

I am currently reading from an ini file with a key/value pair. i.e.

isValid = true 

When get the key/value pair I need to convert a string of 'true' to a bool. Without using boost what would be the best way to do this?

I know I can so a string compare on the value ("true", "false") but I would like to do the conversion without having the string in the ini file be case sensitive.

Thanks

like image 740
Wesley Avatar asked Aug 31 '10 21:08

Wesley


People also ask

How do I convert string to Boolean?

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 an int 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.

What is std::string in C?

The std::string class manages the underlying storage for you, storing your strings in a contiguous manner. You can get access to this underlying buffer using the c_str() member function, which will return a pointer to null-terminated char array. This allows std::string to interoperate with C-string APIs.

How do you turn a variable into a Boolean?

We convert a Number to Boolean by using the JavaScript Boolean() method. A JavaScript boolean results in one of the two values i.e true or false. However, if one wants to convert a variable that stores integer “0” or “1” into Boolean Value i.e “true” or “false”.


1 Answers

Another solution would be to use tolower() to get a lower-case version of the string and then compare or use string-streams:

#include <sstream> #include <string> #include <iomanip> #include <algorithm> #include <cctype>  bool to_bool(std::string str) {     std::transform(str.begin(), str.end(), str.begin(), ::tolower);     std::istringstream is(str);     bool b;     is >> std::boolalpha >> b;     return b; }  // ... bool b = to_bool("tRuE"); 
like image 189
Georg Fritzsche Avatar answered Sep 17 '22 14:09

Georg Fritzsche