The last time I was making a program, I wanted to input from user a boolean answer (to save space ;)) An input of 0/1 works good (0-false) and (1-true), but if the user inputs the boolean values as "true" and "false", it comes out to be an error.
So, are there any ways of doing so.?
I believe, that the strings "true" and "false" are defines using #define in the header files because of which the input is creating an error. Am i correct.?

Recommended Answers

All 5 Replies

Those #define true 1 and #define false 0 are just preprocessor macros which will find and replace all true and false and replace them with 1 and 0 respectively.

boolalpha and noboolalpha work for cin too:

#include <iostream>

using namespace std;

int main()
{
    bool awesome = false;
    cout << "Are you awesome? ";
    if (!(cin >> boolalpha >> awesome))
    {
        cin.clear();
        cin >> noboolalpha >> awesome;
    }
    if (awesome)
        cout << "You *are* awesome!" << endl;
    else
        cout << "Loser" << endl;
}

Ok, so I was correct that they are defined using preprocessor #define. ;)
So, I assume there ain't any solution to getting the input as "true" and making the program think it to be 1 except than using strings...

Ok, so I was correct that they are defined using preprocessor #define.

No, true and false are keywords.

So, I assume there ain't any solution to getting the input as "true" and making the program think it to be 1 except than using strings...

You want to type "true" or "false" as input and have cin recognize it as a bool, right? Did you even read my answer?

@rpdm: sorry, but actually at that time I could not at all understand what were these 'boolalpha' and 'noboolalpha'.. now some google search has shown me cpluscplus and cplusplus/boolalpha which says that these are stream manipulators..
And yes, can anyone please tell how are keywords implemented. Like, these stream manipulators are implemented like..

ios_base& boolalpha ( ios_base& str );

Please try to keep the language simple, cause I have not yet studied compiler design but was just curious to know..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.