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 #include #include #include 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!). */ }
Solution
#include
#include
#include
#include
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