boolean expression

Oct 18, 2009 at 12:07am
In my assignment, I am required to ask the user a question where they respond (y/n) yes or no. I need to convert 'y' to (boolean) true and ''n' to (boolean) false but i am not sure how to do this. Any help would be appreciated.

Thanks
Oct 18, 2009 at 12:57am
Post the code you have so far in [code] tags
Oct 18, 2009 at 12:58am
Well, I'm not very familiar with c++, but I just read something that might be what you need.

In the piece of code I read, there is the boolean type bool (just like an int or a char), that can receive the values
false or true.

I guess you can create a variable

/*******************************************************/
char answer_char;
bool answer_boolean;

std::cin >> char;
if(answer_char == 'y') answer_boolean = true;
if(answer_char == 'n') answer_boolean = false;
/********************************************************/

From what I know about C, true and false are not defined values, and I don't know if there is the variable type bool
(but I'm talking about C, not C++)

So, I hope it helps.
Oct 18, 2009 at 8:41am
I need to convert 'y' to (boolean) true and ''n' to (boolean) false
What if the user enters something different?
Oct 18, 2009 at 7:18pm
I know I'm a newbie when it comes to c++ programming and probably shouldn't give out my codes as they may be faulty, but maybe something like this should help you:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

int main()
{
    char c;
    bool bb;

    do {
        cout << "blabla (y/n) ";
        cin >> c;
    } while (!strchr("yn", tolower(c)));

    tolower(c)=='y'?bb=true:bb=false;


    cout << (bb?"true":"false");
}
Oct 18, 2009 at 8:40pm
line 14 should be bb = ( tolower(c) == 'y' );
and line 17 cout << boolalpha << bb;
Topic archived. No new replies allowed.