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 . . .
//letterGuessexercise.cpp – allows the user to guess a letter chosen
//randomly by the computer
#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
The only problem I spotted was in your if statements. You're using a single equals sign, meaning assign, instead of a double equals sign, meaning 'is it equal to?'. After I made those changes, the program works beautifully.
Also of note, you may want to change cout << "You guessed the correct number" << endl; to cout << "You guessed the correct letter" << endl; ;/
EDIT:
Almost forgot. Your random number, should be from 0 to 25, to correspond to the letters in the string. Change randomNumber = 1 + rand() % (26 - 1 + 1); to randomNumber = rand() %26;