Reputation: 23
I'm just trying some different things coding a rock, paper, scissors game using class/functions. Everything is working out just fine except displaying the results of the outcome of how many times the user won, computer won, and number of ties.
I am coding this in vs-code. I looked up some examples on how to return more than one value and found that helpful. I am currently using pointers to do this method, however I am not sure if it is limited based off the outcome of the code.
void winner(int* U, int* C, int* T)
{
*U = userWin
*C = compWins;
*T = numTies;
if(compChoice == userChoice){
std::cout << "It's a tie!\n";
numTies++;
}
else if(userChoice == 'P' && compChoice == 'R'){
std::cout << "You win! Paper covers rock.\n";
userWins++;
}
else if(userChoice == 'S' && compChoice == 'R'){
std::cout << "Computer wins! Rock beats scissors.\n";
compWins++;
}
else if(userChoice == 'S' && compChoice == 'P'){
std::cout << "You win! Scissors beats paper.\n";
userWins++;
}
else if(userChoice == 'R' && compChoice == 'P'){
std::cout << "Computer wins! Paper covers rock.\n";
compWins++;
}
else if(userChoice == 'R' && compChoice == 'S'){
std::cout << "You win! Rock beats scissors.\n";
userWins++;
}
else if(userChoice == 'P' && compChoice == 'S'){
std::cout << "Computer wins! Scissors beats paper.\n";
compWins++;
}
else std::cout << "Invalid input.\n";
std::cout << "\n";
}
int main(){
rps obj;
char char1('y');
int userWins;
int compWins;
int numTies;
std::cout << "THIS IS A GAME OF ROCK, PAPER, SCISSORS!\n";
do{
obj.player();
obj.computer();
obj.winner(&userWins, &compWins, &numTies);
std::cout << "Enter y to play again or anything else to win: ";
std::cin >> char1;
std::cout << "\n";
}while(char1 == 'y' || char1 == 'Y' );
obj.results();
...
Please enter Rock, Paper, or Scissors - 'R' for Rock, 'P' for Paper, 'S' for Scissors: R
The computer chose scissors.
You win! Rock beats scissors.
Enter y to play again or anything else to win: n
Here are the results...
YOU: 1 COMPUTER: -416437631 TIES: 32769
The outcome of the code prints out the expected values for how many times the user won. However, it seems to be printing out memory locations for the computer number of wins, and number of ties.
Upvotes: 1
Views: 48
Reputation: 1
In the main function, you need to initialise your int variables with initial values of '0'. This will prevent the compiler to give those variables, junk values you see there.
int main(){
rps obj;
char char1('y');
int userWins=0;
int compWins=0;
int numTies=0;
...
Upvotes: 0
Reputation: 24102
You forgot to initialize your variables. In main
, change the declarations to:
int userWins = 0;
int compWins = 0;
int numTies = 0;
Then, in winner
, get rid of:
*U = userWin
*C = compWins;
*T = numTies;
and change:
userWins++;
to:
(*U)++;
and similarly for the other counters.
Upvotes: 1