【问题标题】:Why is scanf working abnormally for bool input in C?为什么scanf在C中的布尔输入工作异常?
【发布时间】:2019-06-12 07:29:46
【问题描述】:

我正在尝试获取 3 个 bool 变量和 1 个 int 变量的输入。即使我输入正确,它的行为也不正确。

我使用%d 作为stdbool.hbool 的格式说明符,正如@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 很多。您是否错过了对该答案的评论,该评论确切地解释了它有什么问题?

标签: c scanf stdbool


【解决方案1】:

bool 没有格式说明符,拥有一个没有多大意义。用户会输入什么"true"?您不能将%d 用于除int 之外的任何其他类型。

如果您出于某种原因需要从标准输入获取布尔输入,请使用int10,然后将其转换为bool。例如:

int living; 
scanf("%d", &living);
bool is_living = living;

intbool 的转换将自动将任何非零值转换为true 并将零转换为false

【讨论】:

    【解决方案2】:

    bool 没有格式说明符。 因为对于bool,它的外观并不清楚。

    有很多可能性:

    • 是/否
    • 是/否
    • 真/假
    • t/f
    • 上述任何不同的案例版本
    • 当地人呢?
    • 1/0

    与数字及其不同格式不同,上述可能性具有不同的语义。因此,不希望使用单个说明符来支持所有这些。

    所以如果你想支持它,你必须自己选择和实现它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多