I am trying to write a code for the game, rock-paper-scissors.
I recently just learned how to use a function to get user input and decided to try it here.
int getInput()
{
int val;
cin >> val; //only values from 0 to 2
return val
}
int main()
{
int userChoice;
while(userChoice = getInput()){//I get a warning here
srand(time(NULL)); //always randon numbers
int computer_choice = rand() % 3;
switch(userChoice) {
case:0
//compare with computer_choice
break;
case:1
//compare with computer_choice
break;
case:2
//compare with computer_choice
break;
}
}
}
Now, I have two questions:
Firstly, is using userChoice = getInput()
as a parameter for my While Loop good practice? I am skeptical because of the warning I get which is this:
suggest parentheses around assignment used as truth value
I believe this means, this parameter returns true. Using while(true)
directly produces an infinite loop.
I want to keep the game going until the user decides to quit. I could easily have used while(cin >> userChoice)
but like I mentioned earlier, I am looking to apply what I recently learned or is this just a case where directly using while(cin >> userChoice)
is more pragmatic?
Secondly, the loop breaks when the userChoice == 0
but other choices work. Is this because 0 returns false and so the while parameter is passed a False
value and then breaks?
Thanks