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
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".
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.
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.
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”.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With