C++ Simple hangman game

To compare the strings of word and guess, you can iterate over the characters in a for-loop, and check if there is a match

string word  = "hangman";
string guess = "mansomething";
string underscore = string(word.size(), '_'); // init a string with underscores equal to the length of 'word'

// iterate over the characters in word and guess
for (size_t i = 0, iend = min(word.size(), guess.size()); i < iend; i++) {
    if (word[i] == guess[i])
        underscore[i] = word[i];  // if the characters match at position i, update the underscore.
}

cout << underscore << endl;

Afterwards, underscore contains the following

_an____

Leave a Comment

tech