As mentioned in the comment:
You do already similar thing with int letterFill (char guess, string secretword, string &guessword) which you are using from main
Same thing you can do with your code in main and put it into a separate Function. I named it 'MyFunction' of course a better name makes sense.
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;
const int tries = 3;
int letterFill(char, string, string & );
void MyFunction();
int main() {
MyFunction();
return (0);
};
void MyFunction() {
char letter;
int wrong_guesses = 0;
string word;
string words[] = {
"punjab",
"balochistan",
"sindh",
"KPK",
"NWFP"
};
srand(time(NULL));
int n = rand() % 5;
word = words[n];
string unknown(word.length(), '*');
cout << endl;
cout << "Hangman Game";
cout << "\n\nYou have " << tries << " tries to try and guess the word." << endl;
while (wrong_guesses < tries) {
cout << unknown;
cout << "\n\nGuess a letter: ";
cin >> letter;
if (letterFill(letter, word, unknown) == 0) {
cout << endl << "wrong guess" << endl;
wrong_guesses++;
} else {
cout << endl << "letter found. Find other letters." << endl;
}
cout << "You have " << tries - wrong_guesses;
cout << " guesses left." << endl;
if (word == unknown) {
cout << word << endl;
cout << "Congrats! You won the Game";
break;
}
}
if (wrong_guesses == tries) {
cout << "\nSorry, you lose...you've been hanged." << endl;
cout << "The word was : " << word << endl;
}
cin.ignore();
cin.get();
}
int letterFill(char guess, string secretword, string & guessword) {
int i;
int matches = 0;
int len = secretword.length();
for (i = 0; i < len; i++) {
if (guess == guessword[i])
return 0;
if (guess == secretword[i]) {
guessword[i] = guess;
matches++;
}
}
return matches;
}