cqu*_*len 48 c++ string boolean
将std :: string转换为bool的最佳方法是什么?我正在调用一个返回"0"或"1"的函数,我需要一个干净的解决方案来将其转换为布尔值.
Dav*_* L. 87
我很惊讶没有人提到这个:
bool b;
istringstream("1") >> b;
Run Code Online (Sandbox Code Playgroud)
要么
bool b;
istringstream("true") >> std::boolalpha >> b;
Run Code Online (Sandbox Code Playgroud)
Chr*_*ung 45
bool to_bool(std::string const& s) {
return s != "0";
}
Run Code Online (Sandbox Code Playgroud)
Kor*_*icz 34
这对你来说可能有些过分,但我会使用boost :: lexical_cast
boost::lexical_cast<bool>("1") // returns true
boost::lexical_cast<bool>("0") // returns false
Run Code Online (Sandbox Code Playgroud)
Pot*_*ter 12
您是否关心无效返回值的可能性,或者您不关心.到目前为止,大多数答案处于中间位置,除了"0"和"1"之外还有一些字符串,或许可以理解它们应该如何转换,也许会引发异常.无效输入无法生成有效输出,您不应尝试接受它.
如果您不关心无效的退货,请使用s[0] == '1'.它非常简单明了.如果你必须证明它对某人的容忍,说它将无效输入转换为false,并且空字符串很可能是\0STL实现中的单个字符串,因此它相当稳定.s == "1"也很好,但s != "0"似乎对我很迟钝,使得无效=>真.
如果您确实关心错误(可能应该),请使用
if ( s.size() != 1
|| s[0] < '0' || s[0] > '1' ) throw input_exception();
b = ( s[0] == '1' );
Run Code Online (Sandbox Code Playgroud)
这可以捕获所有错误,对于任何知道C的smidgen的人来说,这也是非常明显和简单的,并且没有什么能更快地执行.
DavidL 的答案是最好的,但我发现自己想同时支持两种形式的布尔输入。所以主题的一个小变化(以 命名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;
}
Run Code Online (Sandbox Code Playgroud)
这支持“0”、“1”、“true”和“false”作为有效输入。不幸的是,我无法找到一种可移植的方式来支持“TRUE”和“FALSE”
小智 5
我会使用它,它可以满足您的要求,并捕获错误情况。
bool to_bool(const std::string& x) {
assert(x == "0" || x == "1");
return x == "1";
}
Run Code Online (Sandbox Code Playgroud)