How to read a bool using std::cin
Asked Answered
C

3

15

I am new to C++ and I was wondering how the function cin in case of a boolean data works. Let's say for instance :

bool a;
cin >> a;

I understand that if I give 0 or 1, my data a will be either true or false. But what happens if I give another integer or even a string ?

I was working on the following code :

#include <iostream>

using namespace std;

int main()
{
    bool aSmile, bSmile;
    cout << "a smiling ?" << endl;
    cin >> aSmile;
    cout << "b smiling ?" << endl;
    cin >> bSmile;
    if (aSmile && bSmile == true)
        cout << "problem";
    else
        cout << "no problem";
    return 0;
}

If I give the values of 0 or 1 for both boolean, there is no problem. But if I give another integer, here is the output :

a smiling ?
9
b smiling ?
problem

I am not asked to enter any value to bSmile, the line cin >> bSmile seems to be skipped. The same happens if I give a string value to aSmile.

What happened?

Cumbersome answered 5/10, 2014 at 14:18 Comment(3)
Try cin.clear() after taking in aSmileNathanielnathanil
This code is fail() for error checking.Anklet
Relevant: #24505082Alpaca
C
16

From cppreference:

If the type of v is bool and boolalpha is not set, then if the value to be stored is ​0​, false is stored, if the value to be stored is 1, true is stored, for any other value std::ios_base::failbit is assigned to err and true is stored.

Since you entered a value that was not 0 or 1 (or even "true" or "false") the stream set an error bit in its stream state, preventing you from performing any further input.

clear() should be called before reading into bSmile. Also, this is a good reason why you should always check if your input suceeded with a conditional on the stream itself.

Carabin answered 5/10, 2014 at 14:34 Comment(9)
It might be worth adding that you can make the errors more obvious with exceptions: cplusplus.com/reference/ios/ios/exceptionsPeatroy
Thanks a lot. With cin.clear before the bSmile input it works for other integers, but it's still not working for strings !Cumbersome
@Cumbersome "Not working" is very vague, you need to show the code and the behavior.Carabin
I just add cin.clear() after the "cin >> aSmile" in the code above. And with a string input, the result is the same as the one without cin.clear() (you can see it above)Cumbersome
@Cumbersome When you say "string input" do you mean you're providing characters as input? Is aSmile still a bool?Carabin
I put "false" in aSmile (while aSmile is a boolean).Cumbersome
@Cumbersome You need to enable boolean string input using cin >> boolalpha.Carabin
Thanks, it worked. But with cin >> boolalpha i can't use both string and integers right ? Is there a way to use them both at the same time or not ?Cumbersome
@Cumbersome The only way I'd know of is to override the std::num_get facilities and incorporate that custom functionality. Either that or read the values into a string and parse the correct value.Carabin
P
0

First of all, in c++, a boolean variable can take only two values, true & false. If you want to enter the value of a boolean later in your program, you can by not initializing the variable eg, bool isMale;

later in your program, if you want to give the boolean variable 'isMale' a value, you can do so by ..

cin >> isMale;

But then make sure the value you enter is either true or false, else the program will throw an error

Phyla answered 16/9, 2021 at 0:57 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Gumboil
R
0

Even if @David G has answered the question on how it works, I wanted to add a way on how to read a boolean using std::cin which might be useful for others to understand and use.

Source: https://cplusplus.com/forum/beginner/228042/

I have a simple function to get a bool from the user like this:

bool getBoolFromUser(const std::string& name)
{
  std::cout << "Is " << name << " smiling?  (Y=1/N=0) : " << std::endl;

  bool setValue;
  if (std::cin >> setValue) return setValue;  // Boolean read correctly

  // Badly formed input: failed to read a bool
  std::cout << "Wrong value. Only 1 or 0 is accepted." << std::endl;
  std::cin.clear();                // Clear the failed state of the stream
  std::cin.ignore(1000000, '\n');  // Extract and discard the bad input

  return getBoolFromUser(name);  // Try again
}

Later in your main you can use it like so:

int main(int argc, char* argv[])
{ 
  const bool aSmile = getBoolFromUser("a");
  const bool bSmile = getBoolFromUser("b");
  
  if (aSmile && bSmile)
    std::cout << "problem" << std::endl;
  else
    std::cout << "no problem" << std::endl;
  return 0;
}

I hope this helps. :)

Randers answered 28/5, 2024 at 6:16 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.