pranavk
pranavk

Reputation: 1845

Format specifier in scanf for bool datatype in C

I am using bool datatype in C std99 whose definitions are defined in <stdbool.h>. Now I want the user to give me input. What format specifier I must use in scanf to input the boolean value of 1 byte from the user and then manipulate it afterwards in my program.

Upvotes: 26

Views: 55524

Answers (3)

reichhart
reichhart

Reputation: 889

There is no bool format specifier. There cannot be a bool format specifier because it depends strongly on your input.

Your actual question is not about a specifier for bool because there are no "bools" in human languages (which somewhat is most probably your input). Human languages know chars and numbers and more. For those we have format specifiers.

The actual question is how your bool values show up in your input:

  • Is it 1 or 0?
  • TRUE or false?
  • yEs or nO?

Depending on your input you need to choose a matching format specifier. And then distinguish between both bool values.

Example for 1 and 0 as bool representation in your input:

bool b;
int i;
printf("1/0:\n");
scanf("%d", &i);
if (i) {
  b = 1;
} else {
  b = 0;
}

Here an input of 2 would be considered as 1. Hence if you want a strict implementation then you need to do error checking/handling that only 1 or 0 is in your input.

Disclaimer: scanf() is unsafe and insecure. Don't use it! This example is just a demo showing the method of translation input to bool.

Upvotes: 0

Shantanu105
Shantanu105

Reputation: 1

There is no direct way of taking input from users as Boolean . However, we can use a temporary variable and use if-else if statements to take input from users and store that in form of Boolean.

  • For this we have to use <string.h> and its built in function strcmp

Here's how it goes:

#include <stdio.h>
#include <stdbool.h>
#include <string.h>

int main() {
    bool x;
    int temp;
    char y[5];

    printf("Enter Boolean Input True or False: - \n");
    scanf("%s", &y);

    if(strcmp(y, "True") == 0){
        temp = 1;
    }

    else if(strcmp(y, "False") == 0){
        temp = 0;
    }

    x = temp;

    printf("%d", x);

    return 0;
}

You can see the output in this image

1

Upvotes: -1

ouah
ouah

Reputation: 145899

There is none.

Use a temp object as the size of _Bool is implementation dependent.

#include <stdbool.h>
#include <stdio.h>

bool b;
int temp;

scanf("%d", &temp);
b = temp;

Upvotes: 33

Related Questions