将布尔值转换为 C++ 中的文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29383/
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
Converting bool to text in C++
提问by Jason Baker
Maybe this is a dumb question, but is there any way to convert a boolean value to a string such that 1 turns to "true" and 0 turns to "false"? I could just use an if statement, but it would be nice to know if there is a way to do that with the language or standard libraries. Plus, I'm a pedant. :)
也许这是一个愚蠢的问题,但是有没有办法将布尔值转换为字符串,使 1 变为“真”而 0 变为“假”?我可以只使用 if 语句,但很高兴知道是否有办法使用语言或标准库来做到这一点。另外,我是个书呆子。:)
回答by graham.reeds
How about using the C++ language itself?
如何使用 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;
UPDATE:
更新:
If you want more than 4 lines of code without any console output, please go to cppreference.com's page talking about std::boolalpha
and std::noboolalpha
which shows you the console output and explains more about the API.
如果您想要 4 行以上的代码而没有任何控制台输出,请访问cppreference.com 的页面std::boolalpha
,std::noboolalpha
其中显示了控制台输出并解释了有关 API 的更多信息。
Additionally using std::boolalpha
will modify the global state of std::cout
, you may want to restore the original behavior go here for more info on restoring the state of std::cout
.
此外,使用std::boolalpha
将修改 的全局状态std::cout
,您可能想要恢复原始行为,请点击此处了解有关恢复 的状态的更多信息std::cout
。
回答by OJ.
We're talking about C++ right? Why on earth are we still using macros!?
我们在谈论 C++ 对吗?为什么我们还在使用宏!?
C++ inline functions give you the same speed as a macro, with the added benefit of type-safety and parameter evaluation (which avoids the issue that Rodney and dwj mentioned.
C++ 内联函数为您提供与宏相同的速度,并增加了类型安全和参数评估的好处(避免了 Rodney 和 dwj 提到的问题。
inline const char * const BoolToString(bool b)
{
return b ? "true" : "false";
}
Aside from that I have a few other gripes, particularly with the accepted answer :)
除此之外,我还有其他一些抱怨,特别是对于已接受的答案:)
// 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;
}
Cheers :)
干杯:)
@DrPizza: Include a whole boost lib for the sake of a function this simple? You've got to be kidding?
@DrPizza:为了这个简单的功能而包含一个完整的 boost 库?你一定在开玩笑?
回答by DrPizza
C++ has proper strings so you might as well use them. They're in the standard header string. #include <string> to use them. No more strcat/strcpy buffer overruns; no more missing null terminators; no more messy manual memory management; proper counted strings with proper value semantics.
C++ 有合适的字符串,所以你不妨使用它们。它们位于标准标题字符串中。#include <string> 来使用它们。不再有 strcat/strcpy 缓冲区溢出;不再缺少空终止符;不再有杂乱的手动内存管理;具有正确值语义的正确计数字符串。
C++ has the ability to convert bools into human-readable representations too. We saw hints at it earlier with the iostream examples, but they're a bit limited because they can only blast the text to the console (or with fstreams, a file). Fortunately, the designers of C++ weren't complete idiots; we also have iostreams that are backed not by the console or a file, but by an automatically managed string buffer. They're called stringstreams. #include <sstream> to get them. Then we can say:
C++ 也能够将 bool 转换为人类可读的表示形式。我们之前在 iostream 示例中看到了有关它的提示,但它们有点受限,因为它们只能将文本发送到控制台(或使用 fstreams,文件)。幸运的是,C++ 的设计者并不是完全的白痴。我们还有不由控制台或文件支持,而是由自动管理的字符串缓冲区支持的 iostream。它们被称为字符串流。#include <sstream> 来获取它们。那么我们可以说:
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();
}
Of course, we don't really want to type all that. Fortunately, C++ also has a convenient third-party library named Boostthat can help us out here. Boost has a nice function called lexical_cast. We can use it thus:
当然,我们并不是真的想输入所有这些。幸运的是,C++ 还有一个名为Boost的方便的第三方库,可以帮助我们解决这个问题。Boost 有一个很好的函数叫做 lexical_cast。我们可以这样使用它:
boost::lexical_cast<std::string>(my_bool)
Now, it's true to say that this is higher overhead than some macro; stringstreams deal with locales which you might not care about, and create a dynamic string (with memory allocation) whereas the macro can yield a literal string, which avoids that. But on the flip side, the stringstream method can be used for a great many conversions between printable and internal representations. You can run 'em backwards; boost::lexical_cast<bool>("true") does the right thing, for example. You can use them with numbers and in fact any type with the right formatted I/O operators. So they're quite versatile and useful.
现在,可以说这比某些宏的开销更高;stringstreams 处理您可能不关心的语言环境,并创建一个动态字符串(带有内存分配),而宏可以生成一个文字字符串,从而避免了这种情况。但另一方面,stringstream 方法可用于可打印和内部表示之间的大量转换。你可以倒着跑;例如, boost::lexical_cast<bool>("true") 做正确的事情。您可以将它们与数字一起使用,实际上任何类型都可以使用正确格式化的 I/O 运算符。所以它们非常通用且有用。
And if after all this your profiling and benchmarking reveals that the lexical_casts are an unacceptable bottleneck, that'swhen you should consider doing some macro horror.
如果在这一切之后,您的分析和基准测试表明 lexical_casts 是一个不可接受的瓶颈,那么您应该考虑做一些宏观恐怖。
回答by Shadow2531
This should be fine:
这应该没问题:
const char* bool_cast(const bool b) {
return b ? "true" : "false";
}
But, if you want to do it more C++-ish:
但是,如果你想做更多的 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";
}
回答by dwj
If you decide to use macros (or are using C on a future project) you should add parenthesis around the 'b' in the macro expansion (I don't have enough points yet to edit other people's content):
如果您决定使用宏(或在未来的项目中使用 C),您应该在宏扩展中的“b”周围添加括号(我还没有足够的点数来编辑其他人的内容):
#define BOOL_STR(b) ((b)?"true":"false")
This is a defensive programmingtechnique that protects against hidden order-of-operations errors; i.e., how does this evaluate for allcompilers?
这是一种防御性编程技术,可以防止隐藏的操作顺序错误;即,这如何评估所有编译器?
1 == 2 ? "true" : "false"
compared to
相比
(1 == 2) ? "true" : "false"
回答by dwj
I use a ternary in a printf like this:
我在 printf 中使用三元如下:
printf("%s\n", b?"true":"false");
If you macro it :
如果你宏它:
B2S(b) ((b)?"true":"false")
then you need to make sure whatever you pass in as 'b'
doesn't have any side effects. And don't forget the brackets around the 'b'
as you could get compile errors.
那么你需要确保你传入的任何东西'b'
都没有任何副作用。并且不要忘记 周围的括号,'b'
因为您可能会遇到编译错误。
回答by Federico Spinelli
With C++11 you might use a lambda to get a slightly more compact code and in place usage:
使用 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);
Prints:
印刷:
string to print -> true
回答by ewd
Without dragging ostream into it:
无需将 ostream 拖入其中:
constexpr char const* to_c_str(bool b) {
return
std::array<char const*, 2>{"false", "true "}[b]
;
};
回答by Erwan Guiomar
This post is old but now you can use std::to_string
to convert a lot of variable as std::string
.
这篇文章很旧,但现在您可以使用std::to_string
将很多变量转换为std::string
.
http://en.cppreference.com/w/cpp/string/basic_string/to_string
http://en.cppreference.com/w/cpp/string/basic_string/to_string
回答by UIResponder
Use boolalpha
to print bool to string.
用于boolalpha
将布尔值打印到字符串。
std::cout << std::boolalpha << b << endl;
std::cout << std::noboolalpha << b << endl;