从std :: string转换为bool

将std :: string转换为bool的最佳方法是什么? 我正在调用一个返回“0”或“1”的函数,我需要一个干净的解决scheme,把它变成一个布尔值。

它可能会矫枉过正,但我​​会使用boost :: lexical_cast

boost::lexical_cast<bool>("1") // returns true boost::lexical_cast<bool>("0") // returns false 

我很惊讶,没有人提到这个:

 bool b; istringstream("1") >> b; 

要么

 bool b; istringstream("true") >> std::boolalpha >> b; 
 bool to_bool(std::string const& s) { return s != "0"; } 

要么你在意无效的返回值的可能性,要么你不在乎。 到目前为止,大多数答案都处于中间地带,除了“0”和“1”之外,还有一些string可能会合理化,如何转换,或者抛出exception。 无效的input不能产生有效的输出,你不应该试图接受它。

如果您不在乎无效的退货,请使用s[0] == '1' 。 这是非常简单明了的。 如果你必须certificate它对某人的容忍,那么说它将无效input转换为false,并且在你的STL实现中空string很可能是一个单独的\0 ,所以它是相当稳定的。 s == "1"也不错,但是s != "0"对我来说似乎是愚蠢的,使得invalid => 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());

写一个免费的function:

 bool ToBool( const std::string & s ) { return s.at(0) == '1'; } 

这是关于最简单的事情,但你需要问自己:

  • 一个空string应该返回什么? 上面的版本抛出一个exception
  • “1”或“0”以外的字符应该转换为什么?
  • 是一个多个字符的string是函数的有效input吗?

我确定还有其他人 – 这是APIdevise的喜悦!

我会用这个,这是你想要的,并捕获错误的情况。

 bool to_bool(const std::string& x) { assert(x == "0" || x == "1"); return x == "1"; } 

我会改变丑陋的函数,首先返回这个string。 这是bool的目的。

尝试这个:

 bool value; if(string == "1") value = true; else if(string == "0") value = false; 
 bool to_bool(std::string const &string) { return string[0] == '1'; } 

这里有一个类似于凯尔的方式,除了它处理前面的零和东西:

 bool to_bool(std::string const& s) { return atoi(s.c_str()); } 

你总是可以将返回的string包装在处理布尔string的概念的类中:

 class BoolString : public string { public: BoolString(string const &s) : string(s) { if (s != "0" && s != "1") { throw invalid_argument(s); } } operator bool() { return *this == "1"; } } 

调用这样的东西:

 BoolString bs(func_that_returns_string()); if (bs) ...; else ...; 

如果违反关于"0""1"的规则,将会抛出invalid_argument