Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ While Loop termination with function

scratching my head on this as it was working just fine earlier but when I went to add some other functions suddenly my program freaked out and I can not get it back to what it was.

class has me writing a rock/paper/scissors program to go up against a computer, any help with why the loop keeps terminating itself would be wonderful

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;


void RPSout(char);
int RPScomp();

int main() {

    char choice;
    int endit=0;

    while (endit == 0)
    {
        cout << "\n\n\tReady to play Rock/Paper/Scissors against the computer??(please choose R/P/S)(Q to quit)\n";
        cin >> choice;

        RPSout(choice);

        if (choice=='Q'||'q')
            {endit=1;}
    }
    return 0;
}


void RPSout(char choose)
{
    int RPS =0;
    int comp=0;
    switch (choose)
    {
    case 'R':
    case 'r':
    {
        cout <<"Your choice: Rock";
        break;
    }
    case 'P':
    case 'p':
    {
        cout <<"Your choice: Paper";
        break;
    }

    case 'S':
    case 's':
    {
        cout << "Your choice: Scissors";
        break;
    }

    case 'Q':
    case 'q':
    {
        cout << "Bye Bye Bye";
        break;
    }

    default:
        cout<<"You enter nothing!"<<endl;
        cout << "The valid choices are R/P/S/Q)";
    }
    return;
}

int RPScomp()
{
int comp=0;
const int MIN_VALUE =1;
const int MAX_VALUE =3;
    unsigned seed = time(0);

    srand(seed);

    comp =(rand() % (MAX_VALUE - MIN_VALUE +1)) + MIN_VALUE;
    return comp;
}
like image 716
AncientAnubis Avatar asked Feb 04 '23 15:02

AncientAnubis


2 Answers

if (choice=='Q'||'q')

This is equivalent to

if ((choice == 'Q') || 'q')

Which is almost certainly not what you want. 'q' is a non-zero char literal, which is "truthy" and so this expression will never be false. It's akin to writing if (choice == 'Q' || true).

The solution is:

if (choice=='Q' || choice=='q')
like image 108
cdhowie Avatar answered Feb 16 '23 05:02

cdhowie


The statement

if (choice=='Q'||'q')

always tests true and therefore sets your flag to terminate the loop.

Try:

if (choice=='Q'||choice=='q')
like image 24
Phil Brubaker Avatar answered Feb 16 '23 06:02

Phil Brubaker