什么是将std :: string转换为bool的最佳方法?我正在调用一个返回“0”或“1”的函数,我需要一个简洁的解决方案将其转换为布尔值。
我很惊讶没有人提到这个:
bool b;
istringstream("1") >> b;
或者bool b;
istringstream("true") >> std::boolalpha >> b;
bool to_bool(std::string const& s) {
return s != "0";
}
对于你来说可能有些过头了,但我建议使用boost::lexical_cast
boost::lexical_cast<bool>("1") // returns true
boost::lexical_cast<bool>("0") // returns false
boost::bad_lexical_cast
异常。 - C. K. Young你要么在意可能出现的无效返回值,要么不在意。到目前为止,大多数答案都处于中间地带,捕获一些字符串而不是“0”和“1”,或许会谈论如何进行转换,或许会抛出异常。无效的输入不能产生有效的输出,你不应该试图接受它。
如果你不在意无效的返回值,请使用s[0] == '1'
。这非常简单明了。如果你必须向某人证明其容错能力,请说它将无效的输入转换为false,并且空字符串很可能是你STL实现中的单个\0
,因此相对稳定。s == "1"
也可以,但s != "0"
对我来说似乎很迂腐,并且会使无效输入=> true。
如果你关心错误(并且可能应该),请使用
if ( s.size() != 1
|| s[0] < '0' || s[0] > '1' ) throw input_exception();
b = ( s[0] == '1' );
这可以捕获所有错误,对于懂一点 C 的人来说非常明显和简单,而且没有任何其他方法能够更快。
在C++11中也有std::stoi函数:
bool value = std::stoi(someString.c_str());
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;
}
这支持 "0"、"1"、"true" 和 "false" 作为有效的输入。不幸的是,我无法找到一种可移植的方法来支持 "TRUE" 和 "FALSE"。
std::boolalpha
流提取器(其又依赖于您的区域设置)。如果将字符串转换为小写适用于您,那太好了。 - jwmstd::string lower = s;
std::transform( lower.begin(), lower.end(), lower.begin(), ::tolower );
std::istringstream is( lower );
...
<继续使用之前的逻辑>
- fuzzytrue ? "true" : "false"
。然后,他实际上说三元运算符很令人困惑......是啊,就像15年前你刚刚了解while循环时第一次看到它一样。此外,他的语境好像是在大型代码库中的企业代码(“想象一下阅读无聊、重复的日志文件,一个0在一堆1中有多容易被忽略”),但他却建议使用printf
而不是成熟的日志记录解决方案。 - user904963bool to_bool(const std::string& x) {
assert(x == "0" || x == "1");
return x == "1";
}
bool ToBool( const std::string & s ) {
return s.at(0) == '1';
}
这是可能起作用的最简单的事情,但您需要问自己:
我相信还有其他问题 - 这就是 API 设计的乐趣所在!
at
作为检查非常干净。 - GManNickGat()
也是如此。 - Jerry Coffinstd::string
呢? - UncleBensbool to_bool(std::string const& s) {
return atoi(s.c_str());
}