在C ++中将bool转换为文本

时间:2008-08-27 02:32:35

标签: c++ string boolean

也许这是一个愚蠢的问题,但是有没有办法将布尔值转换为字符串,使得1转为“true”而0转为“false”?我可以使用if语句,但很高兴知道是否有办法用语言或标准库来实现。另外,我是一个学生。 :)

16 个答案:

答案 0 :(得分:109)

如何使用C ++语言本身?

bool t = true;
bool f = false;
std::cout << std::noboolalpha << t << " == " << std::boolalpha << t << std::endl;        
std::cout << std::noboolalpha << f << " == " << std::boolalpha << f << std::endl;

更新:

如果您需要超过4行代码而没有任何控制台输出,请转到cppreference.com's page talking about std::boolalpha and std::noboolalpha,它会显示控制台输出并详细说明API。

此外,使用std::boolalpha会修改std::cout的全局状态,您可能希望恢复原始行为go here for more info on restoring the state of std::cout

答案 1 :(得分:67)

我们正在谈论C ++吗?为什么我们还在使用宏??

C ++内联函数为您提供与宏相同的速度,并具有类型安全性和参数评估的额外好处(这避免了Rodney和dwj提到的问题。

inline const char * const BoolToString(bool b)
{
  return b ? "true" : "false";
}

除此之外,我还有其他一些抱怨,尤其是接受的答案:)

// this is used in C, not C++. if you want to use printf, instead include <cstdio>
//#include <stdio.h>
// instead you should use the iostream libs
#include <iostream>

// not only is this a C include, it's totally unnecessary!
//#include <stdarg.h>

// Macros - not type-safe, has side-effects. Use inline functions instead
//#define BOOL_STR(b) (b?"true":"false")
inline const char * const BoolToString(bool b)
{
  return b ? "true" : "false";
}

int main (int argc, char const *argv[]) {
    bool alpha = true;

    // printf? that's C, not C++
    //printf( BOOL_STR(alpha) );
    // use the iostream functionality
    std::cout << BoolToString(alpha);
    return 0;
}

干杯:)


@DrPizza:为了这个简单的功能,包括一个完整的升级lib?你一定是在开玩笑吗?

答案 2 :(得分:20)

C ++有适当的字符串,所以你也可以使用它们。它们位于标准标题字符串中。 #include&lt; string&gt;使用它们。不再有strcat / strcpy缓冲区溢出;不再缺少空终止符;没有杂乱的手动内存管理;正确计算具有适当值语义的字符串。

C ++还能够将bool转换为人类可读的表示形式。我们之前通过iostream示例看到了它的提示,但是它们有点受限,因为它们只能将文本爆炸到控制台(或者使用fstreams,文件)。幸运的是,C ++的设计者并不是完全白痴;我们还有iostream,它不是由控制台或文件支持,而是由自动管理的字符串缓冲区支持。他们被称为字符串流。 #include&lt; sstream&gt;得到他们。然后我们可以说:

std::string bool_as_text(bool b)
{
    std::stringstream converter;
    converter << std::boolalpha << b;   // flag boolalpha calls converter.setf(std::ios_base::boolalpha)
    return converter.str();
}

当然,我们并不想输入所有内容。幸运的是,C ++还有一个方便的第三方库,名为Boost,可以帮助我们在这里。 Boost有一个很好的函数叫做lexical_cast。我们可以这样使用它:

boost::lexical_cast<std::string>(my_bool)

现在,可以说这比一些宏的开销更高; stringstreams处理你可能不关心的语言环境,并创建一个动态字符串(带内存分配),而宏可以产生一个文字字符串,这避免了这一点。但另一方面,stringstream方法可用于可打印和内部表示之间的大量转换。你可以向后跑;例如,boost :: lexical_cast&lt; bool&gt;(“true”)做正确的事情。您可以将它们与数字一起使用,实际上任何类型都使用正确的格式化I / O运算符。因此,它们非常通用且有用。

如果毕竟你的分析和基准测试显示lexical_casts是一个不可接受的瓶颈,那么当你应该考虑做一些宏恐怖时,就是

答案 3 :(得分:6)

这应该没问题:


const char* bool_cast(const bool b) {
    return b ? "true" : "false";
}

但是,如果你想更多地使用C ++ - ish:


#include <iostream>
#include <string>
#include <sstream>
using namespace std;

string bool_cast(const bool b) {
    ostringstream ss;
    ss << boolalpha << b;
    return ss.str();
}

int main() {
    cout << bool_cast(true) << "\n";
    cout << bool_cast(false) << "\n";
}

答案 4 :(得分:4)

如果您决定使用宏(或在未来的项目中使用C),您应该在宏扩展中的'b'周围添加括号(我还没有足够的点来编辑其他人的内容):

#define BOOL_STR(b) ((b)?"true":"false")

这是一种defensive programming技术,可防止隐藏的操作顺序错误;即,这如何评估所有编译器?

1 == 2 ? "true" : "false"

相比
(1 == 2) ? "true" : "false"

答案 5 :(得分:1)

我在这样的printf中使用了三元组:

printf("%s\n", b?"true":"false");

如果您将其设为宏:

B2S(b) ((b)?"true":"false")

然后你需要确保传递的内容'b'没有任何副作用。并且不要忘记'b'周围的括号,因为您可能会遇到编译错误。

答案 6 :(得分:1)

对于C ++ 11,您可以使用lambda来获得稍微紧凑的代码并就地使用:

bool to_convert{true};
auto bool_to_string = [](bool b) -> std::string {
    return b ? "true" : "false";
};
std::string str{"string to print -> "};
std::cout<<str+bool_to_string(to_convert);

打印:

string to print -> true

答案 7 :(得分:1)

C ++ 20 std::format("{}"

https://en.cppreference.com/w/cpp/utility/format/formatter#Standard_format_specification声称默认输出格式为默认字符串:

auto s6 = std::format("{:6}", true);  // value of s6 is "true  "

和:

可用的bool演示类型为:

  • none,s:将文本表示形式(对或错,或特定于语言环境的形式)复制到输出中。
  • b,B,c,d,o,x,X:使用值为static_cast(value)的整数表示类型。

相关:std::string formatting like sprintf

答案 8 :(得分:0)

此帖已过时但现在您可以使用std::to_string将大量变量转换为std::string

http://en.cppreference.com/w/cpp/string/basic_string/to_string

答案 9 :(得分:0)

使用boolalpha将bool打印到字符串。

std::cout << std::boolalpha << b << endl;
std::cout << std::noboolalpha << b << endl;

C++ Reference

答案 10 :(得分:0)

不将ostream拖入其中:

constexpr char const* to_c_str(bool b) {
   return  
    std::array<char const*, 2>{"false", "true "}[b]
   ;
};

答案 11 :(得分:0)

简单如何?

constexpr char const* toString(bool b)
{
   return b ? "true" : "false";
}

答案 12 :(得分:0)

一个非常快速和干净的解决方案,如果您只执行一次或不想使用 bool alpha 更改全局设置,则直接在流中使用三元运算符,如下所示:

 private suspend fun fetchCharacters() : NetworkState {
 return try {
   val response = apiService.getCharacters()
   if (response.isSuccessful) {
     if (response != null) {
       NetworkState.Success(response.body()!!)
     } else {
       NetworkState.InvalidData
     }
   } else {
     when(response.code()) {
       403 -> NetworkState.HttpErrors.ResourceForbidden(response.message())
       404 -> NetworkState.HttpErrors.ResourceNotFound(response.message())
       500 -> NetworkState.HttpErrors.InternalServerError(response.message())
       502 -> NetworkState.HttpErrors.BadGateWay(response.message())
       301 -> NetworkState.HttpErrors.ResourceRemoved(response.message())
       302 -> NetworkState.HttpErrors.RemovedResourceFound(response.message())
       else -> NetworkState.Error(response.message())
     }
   }

 } catch (error : IOException) {
   NetworkState.NetworkException(error.message!!)
 }

三元组很容易学习。它们只是节食的 IF 声明,可以很好地在任何地方丢弃,并且:

bool myBool = true;
std::cout << "The state of myBool is: " << (myBool ? "true" : "false") << std::endl;
enter code here

非常好(有点):

(myBool ? "true" : "false")

您可以找到三元的各种有趣用途,包括此处,但如果您总是使用它们像这样将“真”“假”输出到流中,则应该只打开 boolalpha 功能,除非你有理由不这样做:

{
   if(myBool){
      return "true";
   } else {
      return "false";
   }
}

在代码顶部的某个地方,只需全局启用该功能,这样您就可以将那些甜蜜的布尔值直接放入流中而不必担心。

但不要将其用作一次性使用的标签,如下所示:

std::cout << std::boolalpha;

当一个简单的三元运算符就可以做到时,这是很多不必要的函数调用和浪费的性能开销以及单个布尔值。

答案 13 :(得分:-5)

我同意宏可能是最合适的。我只是掀起了一个测试用例(相信我,我对C / C ++并不擅长,但这听起来很有趣):

#include <stdio.h>
#include <stdarg.h>

#define BOOL_STR(b) (b?"true":"false")

int main (int argc, char const *argv[]) {
    bool alpha = true;
    printf( BOOL_STR(alpha) );
    return 0;
}

答案 14 :(得分:-5)

只要字符串可以直接作为char数组查看,就很难说服std::string将字符串表示为C ++中的一等公民。

此外,无论如何,结合分配和有限性对我来说似乎是一个坏主意。

答案 15 :(得分:-7)

试试这个宏。你希望“true”或false显示的任何地方只需用PRINTBOOL(var)替换它,其中var是你想要文本的bool。

#define PRINTBOOL(x) x?"true":"false"