I have a problem with this code in which an output keeps displaying endlessly and incorrectly. My output should help clarify. I think there is something wrong with my if/else statements. (Program outputs the correct letter first to clarify)
f
Enter your guess: h
The correct letter comes after the letter
Enter your guess: i
The correct letter comes after the letter
Enter your guess: j
The correct letter comes after the letter
Enter your guess: a
The correct letter comes after the letter
Enter your guess: d
The correct letter comes after the letter
Enter your guess: f
The correct letter comes after the letter
Enter your guess: e
The correct letter comes after the letter
Enter your guess: r
The correct letter comes after the letter
Enter your guess: 234
Your guess is not exactly one letter
Press any key to continue . . .
//Ch12AppE04.cpp – allows the user to guess a letter chosen
//randomly by the computer
//Created/revised by <your name> on <current date>
#include <iostream>
#include <string>
#include <algorithm>
#include <ctime>
using std::cout;
using std::cin;
using std::endl;
using std::string;
int main()
{
//declare variables
string letters = "abcdefghijklmnopqrstuvwxyz";
string randomLetter = "";
string guess = "";
int length = 0;
int x = 0;
int randomNumber = 0;
//generate random letter
srand(int(time(0)));
randomNumber = 1 + rand() % (26 - 1 + 1);
randomLetter = letters.substr(randomNumber, 1);
cout << randomLetter << endl;
//get the user's guess
while (length = 1)
{
cout << "Enter your guess: ";
getline(cin, guess);
//validate input
length = guess.length();
if (length != 1)
{
cout << "Your guess is not exactly one letter" << endl;
return 0;
}
transform(guess.begin(), guess.end(), guess.begin(), tolower);
x = guess.compare(0, 1, randomLetter);
if (x = 0)
cout << "You guessed the correct number" << endl;
elseif (x = -1)
cout << "The correct letter comes after the letter" << endl;
else
cout << "The correct letter comes before the letter" << endl;
}
return 0;
} //end of main function