Advertisement
AshfaqFardin

Hangman Game Using an Array

Jun 25th, 2021
1,041
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.22 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <cstdlib>
  4. #include <ctime>
  5. using namespace std;
  6.  
  7. int main(){
  8.     srand(time(0));
  9.     string words[] = { "award", "await", "attend", "bubble", "coding", "spring", "mango", "night", "orange", "reward"};
  10.     int numberOfWords = 10;
  11.     string chosenWord = words[rand() % numberOfWords];
  12.     // cout << chosenWord << endl; // test01
  13.    
  14.     int count = 0;
  15.     char guessedLetter;
  16.     int wordSize = chosenWord.length();
  17.     char finalWord[wordSize];
  18.    
  19.     for(int i = 0; i < wordSize; i++){
  20.         finalWord[i] = '_';
  21.         cout << finalWord[i];
  22.     }
  23.    
  24.     for(int i = 0; i < wordSize + 2; i++){
  25.         cout << "\nGuess a Letter: ";
  26.         cin >> guessedLetter;
  27.         for(int j = 0; j < wordSize; j++){
  28.             if(chosenWord[j] == guessedLetter){
  29.                 finalWord[j] = guessedLetter;
  30.             }
  31.             cout << finalWord[j];
  32.             finalWord[wordSize] = 0;
  33.         }
  34.         if(chosenWord == finalWord){
  35.             cout << "\nCorrect guess!\n";
  36.             break;
  37.         }
  38.         else if(i == wordSize + 1){
  39.             cout << "\nCorrect Answer: " << chosenWord << "\n";
  40.         }
  41.        
  42.     }
  43.  
  44.  
  45.     return 0;
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement