为什么我在使用stdbool.h时在scanf中使用%d会报错?

Why do I get an error when I use %d in scanf when I use stdbool.h?

有时我会在练习编码时使用 stdbool.h。此时如果给scanf的格式修饰符为%d,则会出现如下错误信息。

c:\project\hello\hello\hello.c(11): warning C4477: 'scanf' : format string '%d' requires an argument of type 'int *' but variadic argument 3 has type 'bool'

它似乎可以编译,但它似乎无法在运行时正确识别 true/false 或 0/1 输入。我想知道我是否遗漏了什么。

您正在将 bool(或 _Bool)传递给 scanf。当使用 %d 时,你应该传递一个 int.

的地址

如果您的 bool 名为 x,则使用:

int temporary;
if (1 != scanf("%d", &temporary))
{
    fprintf(stderr, "Error, scanf did not work as expected.\n");
    exit(EXIT_FAILURE);
}
x = temporary;

(对于 exit,请在您的源代码中插入 #include <stdlib.h>。)