y/n interface

Hey, I am not new to c++, but still learning. As in I dont get pointers but I understand classes, functions, and the other main features of c++, so I will try not to sound like a total noob.

Allright here is my question...

Firstly, I know there are probs better ways to do this, I just want to know why this code isnt working. I want to have a y/n response, (enter a y for yes and a n for no type thing). I cant get this to work though. Any ideas as to why this isnt working?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>

using namespace std;

int main()
{
    char letterSelection;

    cout << "Please enter a y for yes or a n for a no" << endl;
    cout << "slection: ";
    cin >> letterSelection;
    int switchInput;
    if(letterSelection = 'y')
        {
            switchInput = 1;
        }
    else
        {
            switchInput = 2;
        }


    switch(switchInput)
        {
            case 1:
                cout << "You selected yes";
                break;
            case 2:
                cout << "You selected no";
                break;
            default:
                cout << "default";
                break;
        }
    return 0;
}

On line 13 you are using the assignment operator, not the comparison ( == )
Allright thanks.
Now that brings me to another question. If I were to use numbers instead of letters. (yes I know I know there is a switch statement and that would be pointless...) But then I could just use an "=" right. Why do I have to use a "==" for this?
= means assignment
== tests for equality

1
2
3
A = 3; // read this as 'assign 3 to A'
A == 1; // read this as 'A is equal to 1'.  Returns FALSE
A == 3; // returns TRUE 
Last edited on
A == 1; // read this as ' IS A equal to 1'. Returns FALS
Rabtherab's reading is technically more accurate.
Relational operators form clauses, not complete questions. Otherwise, "if A==1" would have to be read as "if is A equal to 1?", and "A=A==1" as "A is is A equal to 1?", rather than "if A is equal to 1" and "A is A is equal to 1".

Questions are never made in neither logic nor programming. A question implies that the answer is not known, but state is always known; at least in deterministic computers.
I was going to say something to that effect.
A == 1; // read this as ' IS A equal to 1'. Returns FALS


I would actually read:
1
2
3
if (A == 1) { // If 'A is equal to 1'
     // do something
}


Which is what I think you were driving at.
Last edited on
the assignment in the if clause will always evaluate to true

c++ will assign the 'y' to the letterSelection variable and then implicitly convert it to an integer value (=ascii integral value for character 'y')

now, if an integer is not zero, it is evaluated to true
okay, great. Thanks for all the help
Topic archived. No new replies allowed.