【发布时间】:2019-06-12 07:29:46
【问题描述】:
我正在尝试获取 3 个 bool 变量和 1 个 int 变量的输入。即使我输入正确,它的行为也不正确。
我使用%d 作为stdbool.h 中bool 的格式说明符,正如@taufique 在Format specifier in scanf for bool datatype in C 中所建议的那样
这是我的代码及其行为:
#include <stdio.h>
#include <stdbool.h>
int main( )
{
bool health,sex,living;
int age;
scanf("%d%d%d%d",&sex,&health,&living,&age);
printf("\n%d %d %d %d\n",sex,health,living,age);
}
控制台:
0 1 0 25
0 0 0 25
对于其他一些输入:
1 0 0 26
0 0 0 26
但是,当按照@ouah 在同一 Format specifier in scanf for bool datatype in C 中的建议使用临时整数变量获取输入时,它可以正常工作。
那么为什么 scanf 行为不正常?
PS : 对于某些输入,它确实可以正常工作:
0 0 1 26
0 0 1 26
【问题讨论】:
-
因为对于
%d,您必须传递一个int*,仅此而已。传递其他任何东西都是未定义的行为。如果您不确定要为每个格式说明符传递什么,请查看此处的表格:cplusplus.com/reference/cstdio/scanf -
不是scanf,是你的代码。 taufique 的回答是错误的。
-
@StoryTeller 但它似乎得到了很多人的认可
-
你不知道 bool 对象背后是什么,你不能假设它是 int。我的建议:少用无用的论坛,多看书
-
3 并不多。三是不了解的用户。 20 很多。您是否错过了对该答案的评论,该评论确切地解释了它有什么问题?