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

C++ help please! This game will store the alphabet in a string called letters an

ID: 3769756 • Letter: C

Question

  C++ help please!    This game will store the alphabet in a string called letters and then         select a random letter from the string using a random number as an         index for the substr function.  The game will ask the user to guess a letter,         verify that it is a single letter and then compare the input against the random         letter chosen.  The game will continue until the player guesses the letter.           */       #include <iostream> #include <string> #include <cstdlib> #include <ctime> using namespace std;  int main() {         srand(time(0));   // seed randomizer          // Load string with the alphabet         char ltr = 'a';         string letters="";                  for (int i=0; i<26; i++)                 letters += ltr++;  //Ha ha can you figure out how this works?                  // Game variables                string guess;   // for player input         bool win = false;  // set to true when the player guesses the letter                  // select a random letter         int rnd = rand() % 25;  // integer between 0 and 25         string guessLetter = letters.substr(rnd, 1);    // the random letter as a substring                  // Play game                  /* Write a while statement to repeat until the player guesses correctly.  Remember            to allow guesses of only one letter (use the length() function) and only            small letters (a challenge!).         */  } 

Explanation / Answer

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
srand(time(0)); // seed randomizer

// Load string with the alphabet
char ltr = 'a';
string letters="";
  
for (int i=0; i<26; i++)
letters += ltr++; //Ha ha can you figure out how this works?
  
// Game variables   
string guess; // for player input
bool win = false; // set to true when the player guesses the letter
  
// select a random letter
int rnd = rand() % 25; // integer between 0 and 25
string guessLetter = letters.substr(rnd, 1); // the random letter as a substring
cout<<"letter to be guessed is "<<guessLetter<<endl;
// Play game
  
/* Write a while statement to repeat until the player guesses correctly. Remember
to allow guesses of only one letter (use the length() function) and only
small letters (a challenge!).
*/
while(!win){
cout<<"Guess a single letter : ";
cin>>guess;
cout<<guess<<endl;
if(guess.length()!=1){
cout<<"Wrong input ,Not single letter!!"<<endl;
continue;
}
if(guessLetter == guess){
cout<<"Letter guessed successfully";
win =true;
}
}

}

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