I am writing a code that generates a random number then assign the number to a letter in string letters then user has to guess the letter.
I am trying to loop the the question "Enter one lowercase letter: " if the user enters a letter that does not match randomLetter
, but at the same time I have to make sure the letter is all in lower case (something we haven't learned in class but after searching I found a solution, hopefully it's the right way to go about it).
This while
loop ends if user enters the incorrect lower letter. It does work when the letterGuess
matches randomLetter
.
The other thing I have to do is if user enters an incorrect lower letter then it needs to give feedback that the correct letter comes before or after the entered letter.
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
#include <algorithm>
using namespace std;
//function prototype
void displayNumber(int);
int main()
{
string letters = "abcdefghijklmnopqrstuvwxyz";
string randomLetter;
string letterGuess = "";
string wordLocation = " ";
int randomNumber = 0;
//display random number then assign a random number to letter string
displayNumber(randomNumber);
randomLetter = letters[randomNumber];
while (letterGuess.length() != 1) {
//ask user to enter a lowercase letter and determine if it matches the random letter
cout << "Enter one lowercase letter: ";
getline(cin, letterGuess);
if (all_of(letterGuess.begin(), letterGuess.end(), &::isupper)) {
cout << "letter must be lowercase.";
}
else if (randomLetter.find(letterGuess, 0) == -1) {
cout << "\nYou guessed the correct letter.";
}
else {
wordLocation.insert(0, letters);
} //end if
} //end while
return 0;
} //end of main function
void displayNumber(int num)
{
srand(time(0));
num = (rand() % 26) + 1;
cout << num << endl
<< endl;
} // end of displayNumber function