I have a function called diceRoll() and it itself is working great, but the problem I'm running into is when I try and record the value returned by that function and use it in my main() function.
It helps to look at my code, but what I'm trying to do is record the value output by the diceRoll() and add it to total score. Also what I'm doing is if the diceRoll() returns a value of 1, I want playertotalScore to be returned to 0 and the loop to end.
I hope I've been clear enough. Again to try and restate the issue, I want to be able to test the value returned by diceRoll() function in my program and record it if necessary.
#include <iostream>
#include <ctime>
usingnamespace std;
int diceRoll(){
int value;
value = (rand() % 6) + 1;
return value;
}
int main(){
int playerTotalScore = 0;
char choice = 'a';
srand(time(0));
while (choice != 'p' && choice != 'P'){
cout << "Pass[p] or roll [r]: ";
cin >> choice;
switch (choice)
{
case'P':
case'p':
cout << "Okay, you have " << playerTotalScore << " locked in.\n";
continue;
break;
case'R':
case'r':
cout << "You rolled a ..." << diceRoll() << ".\n";
if (diceRoll() == 1){ //If player gets one. Post Message and set playerTotalScore back to zero.
//Error here aswell diceRoll() isn't above cout statement value but a new call to the function.
//(cout from line 34.)
cout << "Sorry, bub, you are busted back to 0.\n";
playerTotalScore = 0;
continue;
}
else{
playerTotalScore += diceRoll(); // Error on this line. diceRoll() is being called again not maintaing
// value from being called in the above cout statement. (cout from line 34.)
cout << "Thats a total of " << playerTotalScore << " if you pass now.\n";
}
break;
default:
cout << "Invalid input, please enter (p) or an (r).\n";
}
}
cout << "\nEnd of the loop\n";
return 0;
}
you are calling the function, which creates a variable named value and sticks a random number in it. If you want to retain the variable for multiple situations, then create a variable at the beginning of main to store that value, then state:
variable = diceroll();
right before the cout statement that says what you rolled. Then replace every other mention of diceroll with that variable name. That should solve your issue.