Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program that lets the user play hangman. It should have an array of ten

ID: 3588700 • Letter: W

Question

Write a program that lets the user play hangman. It should have an array of ten strings from which it randomly selects one. It should initially print a string of hyphens that is the same length as the string. The program should then prompt the user to pick a letter. If the letter matches any characters in the string, the hyphens in the matching positions should be replaced with that character. Whether or not it's in the string, the letter should be added to the list of letters chosen so far, which should also be printed out for the user. The program should continue asking for a letter and then printing the updated string and characters chosen so far until the string is complete. At that point, the program should congratulate the user and tell them how many guesses it took.

Explanation / Answer

#include<iostream>
#include<string>
#include<stdlib.h>
#include<time.h>

using namespace std;

int main(){

    string a[] = { "happy", "sad","action","thrill","open","close","green","blue","apple","orange"};
    srand(time(NULL));
    string ch;

    string guess = "";
    int ind = rand()%10;
    string data = "" ;
    cout << a[ind] << endl;
    for (int i = 0; i<a[ind].size(); i++)
        data = data + "-";
    int count = 0;
    while(1) {
           cout << data << endl;
           cout << "your guesses:" << guess << endl;
           cout << "Enter your guess:";
           cin >> ch;
           guess = guess + ch;
           count++;
           for (int i = 0; i<a[ind].size(); i++){
              if (a[ind][i] == ch[0]){
                 data[i] = ch[0];
              }
           }
           if (data == a[ind]){
              cout << "The word:" << data << endl;
              cout << "Congratulations ! you guessed it correct ";
              cout << "Your guesses count:" << count << endl;
              break;
           }  
    }
  
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote