0

I am trying to get input for 3 bool variables and 1 int variable. Even though I give input correctly, it is not behaving right.

I am using %d as format specifier for bool in stdbool.h as suggested by @taufique in Format specifier in scanf for bool datatype in C

Here is my code and its behaviour:

#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);
}

Console:

0 1 0 25
0 0 0 25

For some other Input:

1 0 0 26
0 0 0 26

But when using temporary integer variables to get input as suggested by @ouah in the same Format specifier in scanf for bool datatype in C , it works fine.

So why is scanf behaving improperly ?


PS : It does work correctly for some input:

0 0 1 26
0 0 1 26
Hamza Ince
  • 604
  • 17
  • 46
Alagusankar
  • 111
  • 1
  • 8

2 Answers2

1

There is no format specifier for bool and having one doesn't make much sense. What would the user type, "true"? You can't use %d for any other type than int.

If you for some reason need to take boolean input from stdin, use int values 1 or 0, then convert it to bool later. For example:

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

Conversions from int to bool will automatically convert any non-zero value to true and zero to false.

Lundin
  • 195,001
  • 40
  • 254
  • 396
0

There is no format specifier for bool. Because for bool it not that clear how it should look like.

There are many possibilities:

  • yes/no
  • y/n
  • true/false
  • t/f
  • any different case version of the above
  • what about locals?
  • 1/0

Unlike for numbers and their different formats the above possibilities have different semantics. So support them all with a single specifier is not desirable.

So if you want to support it, you have to chose and implement it by yourself.

vlad_tepesch
  • 6,681
  • 1
  • 38
  • 80