booky99
booky99

Reputation: 1456

How to compare if a char or string variable equals a certain string?

I'm trying to get this while loop to work but for some reason, it will automatically "assume" that the user input is wrong.

value is a string (should it be a char?) A,B,C are strings (should they be char?)

void Course::set()
{
    cout << "blah blah blah" << endl;
    cout << "youre options are A, B, C" <<endl;
    cin >> value;

    while(Comp != "A" || Comp != "B" || Comp != "C") 
    {
        cout << "The character you enter is not correct, please enter one of the following: You're options are A, B, C" << endl;
        cin >> value;
    }
    cout << endl;
}

Upvotes: 1

Views: 9080

Answers (3)

DavidRR
DavidRR

Reputation: 19427

As an alternative to the other posted solutions, some might consider this more readable:

while(! (Comp == "A" || Comp == "B" || Comp == "C"))
{
    // do something
}

Also, as others have pointed out, you probably intended:

cin >> Comp;

(Since you are using Comp not value in your while condition.)

Upvotes: 1

Varaquilex
Varaquilex

Reputation: 3463

The mistake you did there was thinking in the daily usage of language while building the if block. As others answered, you should use && for the right logic.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

You should use an && instead of an || in your condition. Currently, your condition is always true, because Comp can be equal to only one of three constants, but not all three at the same time.

Upvotes: 6

Related Questions