max*_*zig 413 c c++ printf boolean
由于ANSI C99存在_Bool或bool通过stdbool.h.但是printfbool 还有一个格式说明符吗?
我的意思是伪代码:
bool x = true;
printf("%B\n", x);
Run Code Online (Sandbox Code Playgroud)
哪个会打印:
true
Run Code Online (Sandbox Code Playgroud)
小智 633
没有.但是,由于任何整数类型比传递给s变量参数时int提升的更短,您可以使用:intprintf()%d
bool x = true;
printf("%d\n", x); // prints 1
Run Code Online (Sandbox Code Playgroud)
但为什么不呢
printf(x ? "true" : "false");
Run Code Online (Sandbox Code Playgroud)
或更好
printf("%s", x ? "true" : "false");
Run Code Online (Sandbox Code Playgroud)
甚至更好
fputs(x ? "true" : "false", stdout);
Run Code Online (Sandbox Code Playgroud)
代替?
izo*_*ica 39
bool没有格式说明符.您可以使用一些现有的说明符打印它来打印整体类型或做一些更奇特的事情:
printf("%s", x?"true":"false");
Run Code Online (Sandbox Code Playgroud)
max*_*zig 30
ANSI C99/C11不包含额外的printf转换说明符bool.
一个例子:
#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;
}
Run Code Online (Sandbox Code Playgroud)
由于它是一个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]
输出:
$ ./main The result is: false (written 21 characters) $ ./main 1 The result is: true (written 20 characters)
jxh*_*jxh 12
在以下传统中itoa():
#define btoa(x) ((x)?"true":"false")
bool x = true;
printf("%s\n", btoa(x));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
594273 次 |
| 最近记录: |