本文翻译自:What is the printf format specifier for bool?
Since ANSI C99 there is _Bool
or bool
via stdbool.h
. 从ANSI C99开始,通过stdbool.h
_Bool
或bool
。 But is there also a printf
format specifier for bool? 但是还有bool的printf
格式说明符吗?
I mean something like in that pseudo code: 我的意思是伪代码中的内容:
bool x = true;
printf("%B\n", x);
which would print: 它将打印:
true
#1楼
参考:https://stackoom.com/question/1AcPb/bool的printf格式说明符是什么
#2楼
There is no format specifier for bool. 没有用于bool的格式说明符。 You can print it using some of the existing specifiers for printing integral types or do something more fancy: 您可以使用一些现有的用于打印整数类型的说明符来打印它,或者做一些更有趣的事情:
printf("%s", x?"true":"false");
#3楼
There isn't. 没有。 But since any integral type shorter than int
is promoted to int
when passed down to printf()
s variadic arguments, you can use %d
: 但是,由于当传递给printf()
的可变参数时,任何比int
短的整数类型都会提升为int
,因此可以使用%d
:
bool x = true;
printf("%d\n", x); // prints 1
But why not 但是为什么不呢
printf(x ? "true" : "false");
or better 或更好
printf("%s", x ? "true" : "false");
or even better 甚至更好
fputs(x ? "true" : "false", stdout);
instead? 代替?
#4楼
You can't, but you can print 0 or 1 您不能,但是可以打印0或1
_Bool b = 1;
printf("%d\n", b);
#5楼
In the tradition of itoa()
: 按照itoa()
的传统:
#define btoa(x) ((x)?"true":"false")
bool x = true;
printf("%s\n", btoa(x));
#6楼
ANSI C99/C11 don't include an extra printf conversion specifier for bool
. ANSI C99 / C11不包含用于bool
的额外的printf转换说明符。
But the GNU C library provides an API for adding custom specifiers . 但是GNU C库提供了用于添加自定义说明符的API 。
An example: 一个例子:
#include <stdio.h>
#include <printf.h>
#include <stdbool.h>
static int bool_arginfo(const struct printf_info *info, size_t n,
int *argtypes, int *size)
{
if (n) {
argtypes[0] = PA_INT;
*size = sizeof(bool);
}
return 1;
}
static int bool_printf(FILE *stream, const struct printf_info *info,
const void *const *args)
{
bool b = *(const bool*)(args[0]);
int r = fputs(b ? "true" : "false", stream);
return r == EOF ? -1 : (b ? 4 : 5);
}
static int setup_bool_specifier()
{
int r = register_printf_specifier('B', bool_printf, bool_arginfo);
return r;
}
int main(int argc, char **argv)
{
int r = setup_bool_specifier();
if (r) return 1;
bool b = argc > 1;
r = printf("The result is: %B\n", b);
printf("(written %d characters)\n", r);
return 0;
}
Since it is a glibc extensions the GCC warns about that custom specifier: 由于它是glibc扩展,因此GCC警告该自定义说明符:
$ gcc -Wall -g main.c -o main main.c: In function ‘main’: main.c:34:3: warning: unknown conversion type character ‘B’ in format [-Wformat=] r = printf("The result is: %B\n", b); ^ main.c:34:3: warning: too many arguments for format [-Wformat-extra-args]
Output: 输出:
$ ./main The result is: false (written 21 characters) $ ./main 1 The result is: true (written 20 characters)