New to C++; need help/advice.

Okay, I'm still new to C++ and I'm trying to make a simple hangman game for my class. Problem is I'm not sure where to go next in my code. Here is 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123

// Hangman.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
#include <cmath>
#include <conio.h>
#include <time.h>

using namespace std;

//
//Hangman Game

string LoadFile() //To load the file
{
	
	string W; //Declare Varibles
	string words[20];
	int count = 0;
	
	ifstream txtfile; //the in file
	
	txtfile.open("words.txt"); //opens file

	for (count=0; !txtfile.eof(); count++)
	{
		getline(txtfile,W);
		words[count] = W;
	}
	int k=(rand()%count); //Picks a random word from file.
	txtfile.close(); //closes file
	
	return words[k];
	
	
}


void RunGame(string word) //Runs the game
{
	int k;
	int count = 0;
	char guess;	
	string letters;
	char x;

	for (k=0; k<word.length();k++)
	{
		letters+= '_';
	}

	cout << word << endl;
	cout << endl;

	while (count!=6)
	{
		for (x=0; x<15; x++)
		{
			cout << "Make a Guess" << endl;
			cin >> guess;

			for (k=0; k<word.length();k++)
			{
				if (guess == word[k])
				{
					cout << "Good Guess!" << endl;
					letters[k] = guess;				
				}

				else 
				{
					cout << "Wrong Letter!" << endl;
					count++;
				}

			}
	
		cout << letters << endl;
		
		

		}
	
	}

	cout << "Game Over! Your word was " << word << endl;



	

}



int _tmain(int argc, _TCHAR* argv[]) //main
{
	cout << "Let's Play HangMan!" << endl;
	
	srand(time(NULL));


	string word= LoadFile();
	RunGame(word);
	cout << endl;


	cout << "Thank You for Playing" << endl;
	
	
	_getch();
	return 0;
}






I'm using Microsoft Visual Studio 2008. I just don't know what I'm doing wrong. I can't seem to get it to stop after you guess the word correctly or how to make you lose after you have six wrong guesses. Please Help!!
Last edited on
A running loop in a game like this should test a simple boolean variable to see if the loop should continue or not. In this case you want to have "if(...)" checks inside of your running loop that would change the boolean to false if one of the conditions you specify are met.

1
2
3
4
5
6
7
8
9
10
while(Running)
{
//Code code code
if(NumberOfGuesses >= 6)
{Win = false;
  Running = false;}

if(letters == word)
{Win = true;
  Running = false;}


This is almost over simplified but you should get the idea.
Last edited on
Or you can use break; to break out of the loop.
Topic archived. No new replies allowed.