If statement in C++ with more than one variable

Viewed 69

I started trying to code in C++ and I made a very simple game. As the game has more than one viable solution, I tried to make an if with more than one variable, but it doesn't seem to work as it doesn't matter the number I type, it always says I'm correct.

int main() {
    string Username;
    cout << "Type your name: "; cin >> Username; cout << endl;
    cout << " Welcome, " << Username << endl;
    cout << "   Guess this number!\n";
    int Ale = 0;
    while(Ale == 0){
        int const ContraC = 134, ContraC2 = 143, ContraC3 = 341, ContraC4 = 314, ContraC5 = 431, ContraC6 = 413;
        int Contra;

        cout << endl;
        cout << "  It is an integer, the three digits add up to 8, and the product of their digits is 12"; cout << endl;
        cout << "  >>>>>>> Type the password and press Enter:"; cin >> Contra;

        if(Contra == ContraC, ContraC2, ContraC3, ContraC4, ContraC5, ContraC6){
            cout << "   Good job! Now press any key to exit the game";
            Ale = 2;
            cout << endl;
            cout << endl;
        } else {
            cout << "   Try again!";
            Ale = 0;
            cout << endl;
        }
    }
    system("pause > nul");

I saw that the error is here if(Contra == ContraC, ContraC2, ContraC3, ContraC4, ContraC5, ContraC6){ because if I change it to this:

if(Contra == ContraC){

it only works with the first variable.

I was wondering how I can use more than one variable in this if. Thank you, ralph.

3 Answers

you can use switch like this to not repeat Contra (instead of ||)

switch(Contra) {
  case ContraC:
  case ContraC2:
  case ContraC3:
  case ContraC4:
  case ContraC5:
  case ContraC6:
     cout << " Good job! Now press any key to exit the game";
     Ale = 2;
     cout << endl;
     cout << endl;
     break;
  default:
     cout << "   Try again!";
     Ale = 0;
     cout << endl;
}

for more details:

see the docs here: https://en.cppreference.com/w/cpp/language/switch

You likely want to use the || operator.

if (Contra == ContraC || 
    Contra = ContraC2 ... ) {
  // ...
}
else {
  cout << "   Try again!";
  Ale = 0;
  cout << endl;
}

Given that you're operating on ints, you can also use a switch statement and take advantage of case fall-through.

switch (Contra) {
  case ContraC:
  case ContraC2:
  // ...
  break;

  default:
  cout << "   Try again!";
  Ale = 0;
  cout << endl;
}

What are you trying to do?

If what you want is "if Contra is equal to ContraC, or Contra is equal to ContraC2, or Contra is equal to ContraC3, etc.", then you should write exactly that.

if(Contra == ContraC || 
   Contra == ContraC2 || 
   Contra == ContraC3 || 
   Contra == ContraC4 || 
   Contra == ContraC5 || 
   Contra == ContraC6) 
{

The reason why what you did isn't a syntax error is that the comma operator exists. It doesn't look like that is what you want though.

Related