Help with a letter guessing game

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 . . .


And my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
//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;
	else if (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 
Last edited on
Topic archived. No new replies allowed.