Hangman program

Pages: 12
Hello, so i am writing a program of hangman but have a few problems that i cant find to solve for i have the right steps but dont know how to resolve the issue. Thsi is what i have so far and needed help. I know i need a do while loop but dont know where to place it and also how to resolve the issue of the string printing it mutiple times. I also need the string to replace with character '*' but i dont know how because if i replace it then all the cahracters in the string will be * instead of its orgianl way.

this is what i need it to show:

enter the string:
"hello world"


***** *****


enter the character you think is on the string:
z

-----------
prints head then body etc.
head


Thanks in advanced


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
  

#include <iostream>
#include <string>

using namespace std;

int main()
{
    // the choice of  letter
    char choice;
    
    // sentence to find out 
    string sentence;
    
    //replace the string with * so user does not see them
    char replace[] = {};
    char star = '*';
    
    
    //print for the user to see error once 
    bool once = false;
    
    bool going = true;
    
    // if all parts of body then user has lost
    int lost = 0;
    
    cout << "Enter the sentence you will like to enter for the search" << endl;
    getline(cin,sentence);
    
    
    cout << "enter the character you want o find in the string" << endl;
    cin >> choice;
    
    
    cout << "---------------------------" <<endl;
    
    for(int i =0; i < sentence.length(); i++){
        
        // bool will show once because you it once
        if (once == false){
            if(choice == sentence[i]){
                cout << "the choice you enter was in the sentece" << endl;
                once = true;
            }
            
            else{
                
                if(going == true){
                   cout << choice << " was not in the sentece " << endl;
                   lost++; 
                   going == false;
                }
                
                cout << "the lost number is " << lost << endl;
                    switch(lost){
                      case 1: cout << "head" << endl;
                      case 2: cout << "body" << endl;
                      case 3: cout << "left leg" << endl;
                      case 4: cout << "right leg" << endl;
                      case 5: cout << "right arm" << endl;
                      case 6: cout << "left arm" << endl;
                    }
                
            }
        }
        
    }
   
    

    return 0;
}
53:26: warning: statement has no effect [-Wunused-value]
You're not setting going to false.
@rezy3312,
With respect ot the problem of displaying the string as asterisks, all you have to do is use string.length() function to get the length, then use a for loop to output asterisks for the length of the string.

Example:
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
// Note: This is a complete, tested program.  
// You can copy and paste this into your compiler, 
// compile and run, and it should not have any issues.
// You should also be able to incorporate it
// into your program without any problems.
#include <string>
#include <iostream>

int main ()
{
	std::string sentence;
	
	std::cout << "Enter the sentence for the search. \n: ";
	getline (std::cin, sentence);

	int len = sentence.length();

	for (size_t i = 0; i < len; ++i)
	{
		// This is so we don't accidentally
		// print a * instead of a space.
		// The string.at (i) function returns
		// the value location "i" in the string.
		if (sentence.at (i) != ' ')
		{
			std::cout << "*";
		}
		else if (sentence.at (i) == ' ')
		{
			std::cout << " ";
		}
		else
		{
			continue;
		}
	}
	std::cout << std::endl;
}
Enter the sentence for the search. 
: this is a test
**** ** * ****


If you have any questions, feel free to ask!
Good luck!
max
@agent max
your code could be a bit simpler.
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
#include <string>
#include <iostream>

int main ()
{
	std::string sentence;
	
	std::cout << "Enter the sentence for the search. \n: ";
	getline (std::cin, sentence);

	for (const char ch: sentence)
	{
		// This is so we don't accidentally
		// print a * instead of a space.
		if (ch == ' ')
		{
			std::cout << ' ';
		}
		else
		{
			std::cout << '*';
		}
	}
	std::cout << std::endl;
}


line 16: int len = sentence.length();
Don't do this. Comparing signed and unsigned values is asking for trouble. Better use auto
Yes it can be:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <string>
#include <iostream>

int main()
{
	std::string sentence;

	std::cout << "Enter the sentence for the search: ";
	std::getline(std::cin, sentence);

	for (const char ch : sentence)
		std::cout << (ch == ' ' ? ch : '*');

	std::cout << '\n';
}

@thmm,
Wait, but the int type is unsigned, right? Also, excuse my ignorance, but what is the auto type? I've heard of it but have never used it before, is it from a newer version of C++? (As in, newer than c++03 which is the version I learned).

@seeplus,
Oh yes, I forgot about the ternary operator; I don't use it much, but it is good to know. Comes in real handy for stuff like this.
agent max wrote:
Wait, but the int type is unsigned, right?
No, int is SIGNED int. To get a unsigned int you need to use unsigned.
https://en.cppreference.com/w/cpp/language/types

agent max wrote:
what is the auto type?
auto is used for type inference, was "added" in C++11. The compiler deduces the type automatically.
https://en.cppreference.com/w/cpp/language/auto

C++11 changed the language a LOT, C++03 is a dinosaur standard. You might as well try making a mnemonic memory circuit using stone knives and bearskins if you don't understand or won't use C++11 (or later) when you can.

C++14 was mostly bug fixes, C++17 made some radical changes/additions to the language, though not as extensive as C++11 did.

C++20, the current standard though no compiler has fully implemented it yet, is more additions and changes that alter the language. C++2b/C++23 is already being worked on.

You have some serious unlearning/relearning to do to understand Modern C++ (C++11 and later).
Oh, I forgot to add that what auto can do keeps getting extended with C++14 and C+20.
https://www.learncpp.com/cpp-tutorial/the-auto-keyword/
@Furry Guy,
Oops, I made a mistake, it wasn't C++03 I learned, it was C++11, which is what I currently use. But I never used the auto type; just never really needed it, I guess.

Hmm, my compiler doesn't have some of that stuff; specifically this:
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

 // only valid starting in C++20
void addAndPrint (auto x, auto y)
{
	std::cout << x + y;
}
int main ()
{
    addAndPrint(2, 3);// int
    addAndPrint(4.5, 6.7);// double  
}
Last login: Mon Mar 15 13:36:56 on ttys001
prandtl:~ agentmax$ cd Desktop/
prandtl:Desktop agentmax$ c++ -std=c++2a -g -o a.out test.cc

test.cc:4:19: error: 'auto' not allowed in function prototype
void addAndPrint (auto x, auto y)
                  ^~~~
test.cc:4:27: error: 'auto' not allowed in function prototype
void addAndPrint (auto x, auto y)
                          ^~~~
2 errors generated.


Even when I use the -std=c++2a flag. Oh well. Needs an update I guess.
@rezy3312,
Sorry we got off topic.

So, I would use @seeplus's code, or @thmm's code, and then add in your prompt to guess a letter that's in the message. Then add another for loop, and use that one to iterate through the string and see if the letter is in it. And if it is in the string, then...um...ok, I'm not too familiar with hangman so if someone else could give some input here that would be great.
ok, first thank you guys so much for the help, second, so I made some changes and found it a simpler way for it to print and replace the characters with *. The only problem now is placing the do-while loop, I know i have to use the do-while loop in the section of the for loop but I'm lost on how to do it. This is what i made the changes on but still prints off the whole body. Please help

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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
#include <iostream>
#include <string>

using namespace std;

//prints the body if any error
int printbody(int);

int main()
{
    
    // the choice of  letter
    char choice;
    
    // sentence to find out 
    string sentence;
    
    //print for the user to see error once 
    bool correct = false;
    bool incorrect = false;
    
    // if all parts of body then user has lost
    int lost = 0;
    
    //main print out

    cout << "----------- WELCOME TO HANGMAN----------------" << endl;
    
    
    cout << "Enter the sentence you will like to enter for the search" << endl;
    getline(cin,sentence);
    
    
    // replace with the string with character *
    for(int i = 0; i < sentence.length(); i++){
        if(isalpha(sentence[i])){
            cout << "*";
        }
        
        if(isspace(sentence[i])){
            cout << " ";
        }
    }
    
    cout << endl;
    
    cout << "enter the character you want to find in the string" << endl;
    cin >> choice;
    
    
        
    cout << "---------------------------" << endl;
    

/* somewhere i need to put do while loop*/



    for(int i =0; i < sentence.length(); i++){
        
        // bool will show once because you it once
        if (correct == false){
            if(choice == sentence[i]){
                cout << "the choice you enter was in the sentece" << endl;
                correct = true;
            }
        }
                
        if(incorrect == false){
           cout << choice << " was not in the sentece " << endl;
           lost++; 
           incorrect == true;
           printbody(lost);
           
           
           // end program if the body is shown
           if(lost >= 7){
               return 1;
           }
        }
                
            
        
        
    }
        
    return 0;
}



int printbody(int part){
    
        switch(part){
            //head
          case 1: cout << "-----------" << endl;
                  cout << "|         |" << endl;
                  cout << "|         |" << endl;
                  cout << "|---------|" << endl;
          break;
          
          // body
          case 2: 
                  cout << "-----------" << endl;
                  cout << "|         |" << endl;
                  cout << "|         |" << endl;
                  cout << "|---------|" << endl;
                  cout << "   |   |  " << endl;
                  cout << "   |   |  " << endl;
          break;
          
          //left arm
          case 3: 
                  cout << "   -----------" << endl;
                  cout << "   |         |" << endl;
                  cout << "   |         |" << endl;
                  cout << "   |---------|" << endl;
                  cout << "      |   |  " << endl;
                  cout << "   ===|   |  " << endl;
                  cout << "  ||  |   |  " << endl;
                  cout << "      |   |  " << endl;
          
          break;
          
          //right arm
          case 4: 
                  cout << "   -----------" << endl;
                  cout << "   |         |" << endl;
                  cout << "   |         |" << endl;
                  cout << "   |---------|" << endl;
                  cout << "      |   |  " << endl;
                  cout << "   ===|   |==" << endl;
                  cout << "  ||  |   | ||" << endl;
                  cout << "  ||  |   | ||" << endl;
          break;
          
          
          //left leg
          case 5: 
                cout << "   -----------" << endl;
                  cout << "   |         |" << endl;
                  cout << "   |         |" << endl;
                  cout << "   |---------|" << endl;
                  cout << "      |   |  " << endl;
                  cout << "   ===|   |==" << endl;
                  cout << "  ||  |   | ||" << endl;
                  cout << "  ||  |   | ||" << endl;
                  cout << "      |   |  " << endl;
                  cout << "      |   |  " << endl;
                  cout << "  ====|---|  " << endl;
                  cout << "  ||         " << endl;
                  cout << "  ||         " << endl;
                  cout << "  ||         " << endl;
                  cout << "  ||         " << endl;
                  
          break;
          
          
          case 6: cout << "   -----------" << endl;
                  cout << "   |         |" << endl;
                  cout << "   |         |" << endl;
                  cout << "   |---------|" << endl;
                  cout << "      |   |  " << endl;
                  cout << "   ===|   |==" << endl;
                  cout << "  ||  |   | ||" << endl;
                  cout << "  ||  |   | ||" << endl;
                  cout << "      |   |  " << endl;
                  cout << "      |   |  " << endl;
                  cout << "  ====|---|====" << endl;
                  cout << "  ||          ||" << endl;
                  cout << "  ||          ||" << endl;
                  cout << "  ||          ||" << endl;
                  cout << "  ||          ||" << endl;
                  cout << "  ||          ||" << endl;
            
            cout << "you lost from the game sorry" << endl;
            
          break;
        }
        
        return part;
}
Last edited on
@rezy3312,
First, I would put all of your switch cases inside curly brackets {} like so:
1
2
3
4
5
6
7
8
case 1:
{
      cout << "-----------" << endl;
      cout << "|         |" << endl;
      cout << "|         |" << endl;
      cout << "|---------|" << endl;
}
break;

This mainly makes it easier to read, but it also takes care of possible errors that can result if you omit the curly brackets.

Also, what @seeplus suggested is even simpler than using isalpha() and isspace().

Ok, you also have an issue on line 72:
hangman.cc:72:22: warning: equality comparison result unused [-Wunused-comparison]
           incorrect == true;
           ~~~~~~~~~~^~~~~~~
hangman.cc:72:22: note: use '=' to turn this equality comparison into an assignment
           incorrect == true;
                     ^~
                     =
1 warning generated.

Need to change that to an "=" not a "==".

And, after researching the Hangman game, I think you should clear the screen before printing the asterisks, so you don't have the original sentence up there.

Also, why do you have your printBody() function return something? All it does is prints stuff to cout, you don't actually use the returned value. So get rid of the return statement and change the function to a void (which means it doesn't return anything).

That's all for now.
Last edited on
@agent max
1
2
3
4
void addAndPrint (auto x, auto y)
{
	std::cout << x + y;
}

you can't use auto with function parameters, only to declare variables and return types.
Until C++20!

You can use them with a lambda though.
@thmm,
See the article Furry Guy posted a link to:
https://www.learncpp.com/cpp-tutorial/the-auto-keyword/

@rezy3312,
Ok, what you need on line 55, where you said "I need a do-while loop," what you need is a search algorithm. I would use a linear search as it is perfect for this sort of thing. Get rid of your for loop in there, (keep the ouput messages and the function call).

Then google "linear search algorithm in c++" and it should give you some good examples.

Good luck!
max
Then google "linear search algorithm in c++"

Better to search for std::find

I didn't know about auto and C++20. Glad I learned sth.
Does any compiler support this already ?
Last edited on
Does any compiler support this already ?

Visual Studio 2019 does.
Does any compiler support this already ?


For a continually updated list of what C++ features are supported by which compiler versions see https://en.cppreference.com/w/cpp/compiler_support

which also covers C++23 support!

Also, for a book that covers the changes introduced with C++20, see

C++20 by Rainer Grimm https://leanpub.com/c20
Last edited on
Thanks everyone.
I managed to compile this example from learncpp.com with VS 2019
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

void addAndPrint(auto x, auto y) // only valid starting in C++20
{
  std::cout << x + y;
}

int main()
{
  addAndPrint(2, 3); // int
  addAndPrint(4.5, 6.7); // double
}
Pages: 12