【问题标题】:Is there a way to convert a bool to string in c++ 20?有没有办法在 C++ 20 中将布尔值转换为字符串?
【发布时间】:2023-01-27 10:02:37
【问题描述】:

我需要将布尔值转换为文本字符串。有谁知道这是怎么做到的吗?

我试着用

(std::string)bool

语法,但没有用。

【问题讨论】:

  • 你期望结果是什么?
  • 好吧,鉴于 bool 只能是两个可能的值,您不认为暴力破解它很简单吗?如果为真,则将字符串设置为“yup”,否则将其设置为“nope”。 if 语句或三元运算符应该可以解决问题,对吧?

标签: c++ string boolean


【解决方案1】:

std::string 没有定义任何到/从 bool 的转换。但是,std::istreamstd::ostream 可以。例如:

std::ostringstream oss;
oss << theBoolValue;
std::string s = oss.str();

默认情况下,将为true输出1,为false输出0。如果您希望结果实际上是 "true""false",您可以使用 std::boolalpha 操纵器:

oss << std::boolapha << theBoolValue;

【讨论】:

    猜你喜欢
    • 2018-09-10
    • 1970-01-01
    • 1970-01-01
    • 2014-03-20
    • 1970-01-01
    • 2023-01-30
    • 1970-01-01
    • 2018-09-07
    • 1970-01-01
    相关资源
    最近更新 更多