C++ 从 std::string 转换为 bool

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2165921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:21:13  来源:igfitidea点击:

Converting from a std::string to bool

c++stringboolean

提问by cquillen

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 boolean value.

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

采纳答案by Kornel Kisielewicz

It'll probably be overkill for you, but I'd use boost::lexical_cast

这对你来说可能有点矫枉过正,但我​​会使用boost::lexical_cast

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

回答by David L.

I am surprised that no one mentioned this one:

我很惊讶没有人提到这一点:

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

or

或者

bool b;
istringstream("true") >> std::boolalpha >> b;

回答by Chris Jester-Young

bool to_bool(std::string const& s) {
     return s != "0";
}

回答by Potatoswatter

Either you care about the possibility of an invalid return value or you don't. Most answers so far are in the middle ground, catching some strings besides "0" and "1", perhaps rationalizing about how they should be converted, perhaps throwing an exception. Invalid input cannot produce valid output, and you shouldn't try to accept it.

您要么关心无效返回值的可能性,要么不关心。到目前为止,大多数答案都处于中间地带,除了“0”和“1”之外,还捕获了一些字符串,可能会合理解释它们应该如何转换,可能会引发异常。无效的输入不能产生有效的输出,你不应该试图接受它。

If you don't care about invalid returns, use s[0] == '1'. It's super simple and obvious. If you must justify its tolerance to someone, say it converts invalid input to false, and the empty string is likely to be a single \0in your STL implementation so it's reasonably stable. s == "1"is also good, but s != "0"seems obtuse to me and makes invalid => true.

如果您不关心无效退货,请使用s[0] == '1'. 这非常简单明了。如果您必须向某人证明其容忍度是合理的,请说它将无效输入转换为 false,并且空字符串可能是\0您的 STL 实现中的单个字符串,因此它相当稳定。s == "1"也很好,但s != "0"对我来说似乎很钝,并且使无效 => 为真。

If you do care about errors (and likely should), use

如果您确实关心错误(并且可能应该),请使用

if ( s.size() != 1
 || s[0] < '0' || s[0] > '1' ) throw input_exception();
b = ( s[0] == '1' );

This catches ALL errors, it's also bluntly obvious and simple to anyone who knows a smidgen of C, and nothing will perform any faster.

这可以捕获所有错误,对于任何了解一点 C 语言的人来说,这也是显而易见和简单的,而且没有什么比这更快的了。

回答by Mike

There is also std::stoi in c++11:

C++11 中还有 std::stoi:

bool value = std::stoi(someString.c_str());

布尔值 = std::stoi(someString.c_str());

回答by Mike

I'd use this, which does what you want, and catches the error case.

我会使用它,它可以满足您的需求,并捕获错误情况。

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

回答by Mike

Write a free function:

编写一个免费函数:

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

This is about the simplest thing that might work, but you need to ask yourself:

这是关于可能有效的最简单的事情,但您需要问自己:

  • what should an empty string return? the version above throws an exception
  • what should a character other than '1' or '0' convert to?
  • is a string of more than one character a valid input for the function?
  • 空字符串应该返回什么?上面的版本抛出异常
  • '1' 或 '0' 以外的字符应该转换成什么?
  • 一个多于一个字符的字符串是函数的有效输入吗?

I'm sure there are others - this is the joy of API design!

我敢肯定还有其他人 - 这就是 API 设计的乐趣!

回答by jwm

DavidL's answeris the best, but I find myself wanting to support bothforms of boolean input at the same time. So a minor variation on the theme (named after std::stoi):

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;
}

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"

这支持“0”、“1”、“真”和“假”作为有效输入。不幸的是,我想不出一种可移植的方式来支持“TRUE”和“FALSE”

回答by rmn

I'd change the ugly function that returns this string in the first place. That's what bool is for.

我会首先更改返回此字符串的丑陋函数。这就是 bool 的用途。

回答by kervin

If you need "true" and "false" string support consider Boost...

如果您需要“true”和“false”字符串支持,请考虑使用 Boost ...

BOOST_TEST(convert<bool>( "true", cnv(std::boolalpha)).value_or(false) ==  true);
BOOST_TEST(convert<bool>("false", cnv(std::boolalpha)).value_or( true) == false);

BOOST_TEST(convert<bool>("1", cnv(std::noboolalpha)).value_or(false) ==  true);
BOOST_TEST(convert<bool>("0", cnv(std::noboolalpha)).value_or( true) == false);

https://www.boost.org/doc/libs/1_71_0/libs/convert/doc/html/boost_convert/converters_detail/stream_converter.html

https://www.boost.org/doc/libs/1_71_0/libs/convert/doc/html/boost_convert/converters_detail/stream_converter.html