Problem with while loop!
Why when i enter 'q' or 'Q' the while loop executes?
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 37 38 39 40 41 42
|
char choice_fj();
int main()
{
int balls;int guess,guesses=0;
char choice;choice=choice_fj();
while((choice!='q')||(choice!='Q'))
{
srand(static_cast<unsigned int>(time(0)));
balls=rand()%900+100;
while(guess<balls || guess>balls)
{
cout<<"Guess: ";cin>>guess;
if(guess<balls)cout<<"Too low"<<endl;
else if(guess>balls)cout<<"Too high"<<endl;
}
cout<<"Congrats!!!"<<endl;
choice=choice_fj();
}
return 0;
}
char choice_fj()
{
char choice;
cout<<"Play-(Y/y)"<<endl;
cout<<"Quit-(Q/q)"<<endl;
cin>>choice;
return choice;
}
|
Last edited on
|
while((choice!='q')||(choice!='Q'))
|
The problem here is that at least one of the two conditions is
always true, hence the complete expression is always true.
It could better be written as
|
while( !(choice=='q' || choice=='Q') )
|
or
|
while((choice!='q') && (choice!='Q'))
|
or
|
while( std::toupper(choice) !='Q' )
|
the last requires
#include <cctype>
aaaaaaaaahaaaaa yes i can't believe i did this again thx :D
Topic archived. No new replies allowed.