Hello fellow students. I’m a little stuck with a simple heads-or-tails game in C++.
So long as the user input for heads or tails is correct then everything works fine. The problem arises when error checking the input (i.e. anything other than “H” or “T”) in the user input function. I have used an ‘OR’ operator to check that the input is either “H” or “T” and if it’s not then it gives an error message and calls the user input function again. My problem is that if the user inputs an invalid first guess, that invalid value remains as is even if your second attempt is valid and despite calling the user input function again.
I suspect the issue lies in calling getUserInput() from within itself. Any advice would be greatly appreciated
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
string getUserInput() { //gets user's heads or tails call and checks validity of input (not working)
string input = "";
cout << "Input H for Heads or T for Tails" << endl; //request input parameters from user
cin >> input;
if (input == "H" || input == "T") { //check validity of input
return input;
} else {
cout << "Invalid input!" << endl;
getUserInput(); //I suspect the problem lies in calling this function from within itself here
};
}
string coinFlip() { //determines heads or tails using built-in pseudo-random number
srand((int)time(0)); //seed random number based on current time
int randomValue = (rand() % 100) + 1; //generate random value from 1 to 100
string result = "";
if ( randomValue % 2) {
result = "H"; //if randomvalue is odd, flip is heads
} else {
result = "T"; //if randomValue is even, flip is tails
};
return result;
}
void compare(string guess, string result) {
if (guess == result) {
cout << "Nice! You called correctly!" << endl;
} else {
cout << "Sorry, you called incorrectly!" << endl;
};
}
int main()
{
string guess = getUserInput();//get user to call heads or tails CHECKING USER INPUT NOT WORKING HERE!!
string result = coinFlip();//flip coin
cout << "Called: " << guess << " Flipped: " << result << endl; //output results for checking
compare(guess,result);//compare call vs flip
return 0;
}