faulty code

closed account (30X1hbRD)
Hi, I'm following a tutorial in a book about game programming and I've managed to get the code to compile properly and it all mostly runs except for the hint function... For some reason it spams the hint constantly and it won't let me end the program... I think it's a problem with the while loop, but I can't figure it out... any help is appreciated

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
59
  #include <iostream>
#include <cstdlib>
#include <time.h>
#include <string>
using namespace std;

int main() {

      enum fields {word, hint, num_fields};
  const int num_word = 5;
  const string words[num_word][num_fields] = {
      {"Lion", "The 'Mane' king of africa."},
	  {"gander", "Take one of these, or a guess."},
	  {"anagram", "A jumbled up word..."},
	  {"twilight", "Nighttime"},
	  {"frontier", "A new place to explore"}
	  
	  };
	  
	  srand(time(0));
	   int choice = (rand() % num_word);
	   string theword = words[choice][word];
	   string thehint = words[choice][hint];
	   
	   string jumble = theword;
	   int length = jumble.size();
	   for (int i = 0; i < length; i++)
	   { int index1 = (rand() % length);
	   int index2 = (rand() % length);
	   char temp = jumble[index1];
	   jumble[index1] = jumble[index2];
	   jumble[index2] = temp;
	   }
	   
	      cout << "Welcome to What's the Word!" << endl;
	   cout << "Unscramble the word to win!" << endl;
	   cout << "Enter hint for a hint!" << endl;
	   cout << "Enter quit if you're bored, or a loser!" << endl;
	   cout <<  "The word you'll be trying to unscramble is...... " << jumble << endl;
	   
	   cout << "Take a Guess!" << endl;
	   string guess;
	   cin >> guess;
	   while ((guess != theword) && (guess != "quit"))
	  {
	    if (guess == "hint") {
		cout << thehint << endl;
		} else {
		cout << "Sorry, that's not correct" << endl;
		cout << "Take a guess : " << endl;
		cin >> guess;}}
		
		
		if (guess == theword)
		{
		  cout << "That's it! You got it!" << endl;
		  cout << "Thanks for playing!" << endl;
		  return 0;
		  }}
If the user enters "hint" they don't get an opportunity to enter a new guess.

These two lines should be executed within the while loop, regardless of what the user entered last time:
1
2
    cout << "Take a guess : " << endl;
    cin >> guess;


Also, (though it doesn't affect the outcome) return 0; should be outside the braces of the last if statement.
Last edited on
closed account (30X1hbRD)
Thank you very much Chervil, I placed it after the else statement still within the while loop and it works fine now! Thanks a ton!
Topic archived. No new replies allowed.