-1

The application asks the user to enter the students major - either math or CIS and I wanted to make it so if the user were to enter something other than those two it would give an error message and prompt the user to enter the major again.

Here is what I have so far:

        cout << "Math or CIS Major: ";
        cin >> major;
            if (major != "math" || major != "Math" || major != "CIS"  || major != "cis") {
            cout << "Invalid major" << endl;
            }

        cout << "Enter students GPA: ";
        cin >> studentGpa;

This will give the invalid major message but it will just move onto the GPA

For some reason I can't remember the basics and this is tripping me up.

Also if someone could guide me in the right direction for an alternative to the ||'s I know this isn't the best way to do this but again I am struggling with coming up with a better way to do this again

freeWind
  • 148
  • 9
  • And variable major is what? An char variable? If yes, only pointers are compared then. – KIIV Oct 08 '15 at 12:29
  • You need a `while` loop around reading and checking of input, checking of and (`&&`) insteaf or (`||`) in the `if`. And to simplify checks you can use `strToLower()` function (read here: http://stackoverflow.com/questions/313970/how-to-convert-stdstring-to-lower-case ). – Ilya Oct 08 '15 at 12:30
  • The if statement translated to english (two conditions omitted for simplicity) says: **If my major is different than math OR different than CIS, then it's invalid.** Do you see why it's wrong? – jrok Oct 08 '15 at 12:31

3 Answers3

2

Replace OR(||) with AND(&&)

if (major != "math" && major != "Math" && major != "CIS"  && major != "cis")
Aswin Murugesh
  • 10,831
  • 10
  • 40
  • 69
1

If you want the user to have to input a valid major then you need to put it into a loop:

std::string major;
std::cout << "Major: ";
std::cin >> major;
while (major != "math" && major != "Math" && major != "CIS"  && major != "cis")
{
    std::cout << "Please enter a valid major!\n";
    std::cout << "Major: ";
    std::cin >> major;
}

This way the program will not continue unless they enter a valid major.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
0

You are confused between OR (||) and AND (&&). Replacing || by && in the IF condition should do the trick.

What your current if statement checks (if A is not equal to B) OR (if A is not equal to C). If B and C are distinct, then A can at max be equal to one of them, or in other words, will always not be equal to at least one of them.

So, your condition will always evaluate to true. The correct term for this is that your if condition is a tautology.

If you want to skip all this and want the code:

if (major != "math" && major != "Math" && major != "CIS"  && major != "cis") {
therainmaker
  • 4,253
  • 1
  • 22
  • 41