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 boole
DavidL's answer is the best, but I find myself wanting to support both forms of boolean input at the same time. So a minor variation on the theme (named after std::stoi):
bool stob(std::string s, bool throw_on_error = true)
{
auto result = false; // failure to assert is false
std::istringstream is(s);
// first try simple integer conversion
is >> result;
if (is.fail())
{
// simple integer failed; try boolean
is.clear();
is >> std::boolalpha >> result;
}
if (is.fail() && throw_on_error)
{
throw std::invalid_argument(s.append(" is not convertable to bool"));
}
return result;
}
This supports "0", "1", "true", and "false" as valid inputs. Unfortunately, I can't figure out a portable way to also support "TRUE" and "FALSE"
Try this:
bool value;
if(string == "1")
value = true;
else if(string == "0")
value = false;