simple word guess game

I'm a newbie trying to create a word guess game and I'm having trouble with the simplest part. I'm trying to create a for loop that checks the string wordToGuess for the char guessletter. The problem is if it prints the statement i amount of times. How can I prevent this but still indicate whether or not the letter is in the string?

for (i = 0; i < WORD.length()-1; i++)
{
if (WORD.at(i) == guessletter)
{

cout << "That's right! The letter " << guessletter << " is in the word." << endl;
}

else{

cout << "You have chosen poorly." << endl;}
}
Please use code tags when posting
http://www.cplusplus.com/articles/z13hAqkS/

if you want the for loop to exit early then use a break; statement

example
1
2
3
4
5
6
if (WORD.at(i) == guessletter)
 {

      cout << "That's right! The letter " << guessletter << " is in the word." << endl;
      break;
 }


btw your for loop is wrong it should look like this for (int i = 0; i < WORD.length(); i++)

and you are probably better off using the string find method
http://www.cplusplus.com/reference/string/string/find/

example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;

int main()
{
	string word = "Hello";
	char guessletter = 'o';

	if (word.find(guessletter) != string::npos)
		cout << "That's right! The letter " << guessletter << " is in the word." << endl;

	cin.ignore();
	return 0;
}
Last edited on
what if the letter is in the word twice? Like l in hello.
If its two letters than i shouldn't give you the whole code so if your stuck try to solve by yourself
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
int main ()
{
	int count =0;
   string word ="hello";
   char guess;
 
   for(int i=0; i<word.length();++i )
   {
   cout<<"Enter a char to guess the word\n";
   cin>>guess;
	   int flag=0;
	   if(count ==4)
	   {
		   cout<<"you guessed the word\n";

	   }
	   for(int j=0; j<word.length();++j)
	   {
	   if(guess==word[j])
	   {
		   cout<<"Letter found\n";
		   count++;
		   flag=1;

	
	   }
	   }
	   if (flag==0) 
	   {
		   cout<<"Letter not found\n";
	   }
   }

  getch();
  return 0;
}
if you wan't to know how many times a letter appears in a string then I would use the count function from the algorithm header file

example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int main()
{
	string hello = "Hello";
	char letter = 'l';
	int charCount = 0;

	charCount = count(hello.begin(), hello.end(), letter);
	
	if (charCount)
		cout << "There are " << charCount << " " << letter << " in " << hello << endl;
	else
		cout << letter << " Not found in " << hello << endl;

	cin.ignore();
	return 0;

}



you may wan't to convert the string to all upper or all lower case letters using toupper or tolower
Last edited on
Topic archived. No new replies allowed.