You must loop through the word letter by letter and see if any of the letters matches the player's guess. If so, then simply place this letter into an array (although I'd rather use a vector instead of a fixed size array).
So something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
std::string theWord = "Hello";
std::vector<char> correctGuess(theWord.size(), '-'); // Creates dynamic array of theWord.size() and initialize each element to - for now.
char guess = ' ';
std::cin >> guess; // Get player guess
for (unsignedint i = 0; i < theWord.size(); ++i) // Loop through the letters
{
if (guess == theWord[i]) // Check to see if guess is contained in the word
{
correctGuess[i] = guess; // If so, store the player's guess into the array
}
}
// Display guessed letters
std::cout << "Letters guessed: \n";
for (unsignedint i = 0; i < correctGuess.size(); ++i)
{
std::cout << correctGuess[i] << "\n";
}
Obviously you'll have to chuck that in within a gameloop.
#include <iostream>
usingnamespace std;
int main()
{
char* word = "rainbow";
int word_length = strlen(word);
char* success_so_far = newchar[word_length];
char ch;
int no_successes = 0;
while(cout << "Please enter a letter: " && cin >> ch )
{
if(strchr(word,ch))
{
cout << "Bingo!\n";
success_so_far[no_successes] = ch;
no_successes++;
}
else
cout << "Letter not found!\n";
cout << "Found so far: " << success_so_far << '\n';
}
delete [] success_so_far;
// the most important Uk marine amd't (hence value of smart pointers)
return 0;
}
Please enter a letter: y
Letter not found!
Found so far:
Please enter a letter: r
Bingo!
Found so far: r
Please enter a letter: t
Letter not found!
Found so far: r
Please enter a letter: o
Bingo!
Found so far: ro
Please enter a letter: w
Bingo!
Found so far: row
Please enter a letter:
If this is some sort of an assignment you were given and you are being restricted to using just fixed size arrays, then you can go with Kemort's example but remember to deallocate the memory that's on the heap (or freestore).