关于字符串:在C ++中将布尔转换为文本

关于字符串:在C ++中将布尔转换为文本

Converting bool to text in C++

也许这是一个愚蠢的问题,但是有什么方法可以将布尔值转换为字符串,以使1变为" true"而0变为" false"? 我可以只使用if语句,但是很高兴知道是否可以使用语言或标准库来执行此操作。 另外,我是一个学徒。 :)


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

1
2
3
4
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;

更新:

如果您需要四行以上的代码而没有任何控制台输出,请转到cppreference.com的页面,该页面讨论std::boolalphastd::noboolalpha,该页面向您显示控制台输出并解释有关API的更多信息。

另外,使用std::boolalpha将修改std::cout的全局状态,您可能想恢复原始行为,请转到此处以获取有关恢复std::cout状态的更多信息。


我们在谈论C ++,对吗?我们到底为什么还在使用宏!

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

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

除此之外,我还有其他一些困扰,尤其是对于公认的答案:)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 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:包括整个boost库是为了实现一个简单的功能?你一定是在开玩笑?


C ++具有适当的字符串,因此您不妨使用它们。它们在标准标题字符串中。 #include 来使用它们。没有更多的strcat / strcpy缓冲区溢出;不再缺少空终止符;不再麻烦的手动内存管理;具有正确值语义的正确计数字符串。

C ++也能够将布尔转换为人类可读的表示形式。之前我们在iostream示例中看到了提示,但由于它只能将文本直接发送到控制台(或使用fstreams,文件),因此它们受到了一定的限制。幸运的是,C ++的设计者并不是白痴。我们还提供了不由控制台或文件支持的iostream,而是由自动管理的字符串缓冲区支持的iostream。它们称为字符串流。 #include 来获取它们。然后我们可以说:

1
2
3
4
5
6
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。我们可以这样使用它:

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

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

并且如果所有这些之后,您的性能分析和基准测试表明lexical_casts是不可接受的瓶颈,那么您就应该考虑进行一些宏观恐怖了。


这应该很好:

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

但是,如果您想做更多C ++式的操作:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#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) <<"
"
;
    cout << bool_cast(false) <<"
"
;
}

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

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

这是一种防御性编程技术,可防止出现隐藏的操作顺序错误。即,这如何评估所有编译器?

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

相比

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

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

1
2
printf("%s
"
, b?"true":"false");

如果您将其宏化:

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

那么您需要确保以'b'身份传递的任何内容都没有任何副作用。并且不要忘记'b'周围的括号,因为这样可能会导致编译错误。


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

1
2
3
4
5
6
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);

印刷品:

1
string to print -> true

无需将ostream拖入其中:

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

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

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

C ++参考


这篇文章很老,但是现在您可以使用std::to_string将很多变量转换为std::string

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


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

此外,将分配和边界结合起来对我来说似乎不是一个好主意。


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

1
2
3
4
5
6
7
8
9
10
#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;
}

试试这个宏。只要要显示" true"或false的任何地方,就用PRINTBOOL(var)替换它,其中var是您想要文本使用的布尔值。

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


推荐阅读