showing a matched character with the rest of the word hidden

I'm trying to take a letter guess from the user. I then want to see if the users guess matches a character in my hidden word. If it does match i want to show the hidden word as asterisks with the matched character revealed.

e.g user guesses - "a"
If hidden word was bat i'd display "*a*"

my code so far:
void userGuess()

{
string userguess;
for (int i = 0; i < getword.length + 1; --i);
cout << "Enter a letter or a guess... ";
cin >> userguess;
if (userguess.length() == 1);
charguess();
else if (userguess == getword);
cout << "Well done!";
//run menu
else
cout << "Wrong!";

}

void charguess()
string getword;
string userguess;
{

string theword = getword;
theword.find(userguess);
if (theword.find(userguess) = true);
//display hidden word with guess
else
cout << "Wrong" << endl;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <string>
#include <iostream>

std::string mask( std::string word, std::string guessed_chars )
{
    std::string masked ;
    for( char c : word ) masked += guessed_chars.find(c) == std::string::npos ? '*' : c ;
    return masked ;
}

int main()
{
    const std::string word = "abracadabra" ;
    std::string guessed_chars ;
    for( char c : "abqcdr" ) if(c)
    {
        guessed_chars += c ;
        std::cout << "guessed: " << guessed_chars
                  << "\nmasked word: " << mask( word, guessed_chars ) << "\n\n" ;
    }
}

http://coliru.stacked-crooked.com/a/89951050805bd904
What's c?
each character in your string.

JLBorges, out of interest would you write something like this:
for( char c : word ) masked += guessed_chars.find(c) == std::string::npos ? '*' : c ;
in production code?
Depends. I generally tend to conform to the existing style conventions of the code-base as a whole.

Unless it is a palooka set up (auto-ident? now what on earth is that? code-review, you say? does it have horns? test-frames? ... etc.) whose religious tenets include: 'if there can be a brace, there must be a brace'.

I bluntly refuse to write code of this kind:
1
2
3
4
5
6
7
8
9
10
11
12
for( char c : word )
{
     if( std::string::npos )
     {
             masked += '*' ; 
     }

     else
     {
             masked += 'c' ;
     } 
}
okay, cheers for the info.
Topic archived. No new replies allowed.