Restarting a loop in C++? - c++

I am in need of assistance with my program. I have to code a three-round word scramble program using 10 keywords that will appear scrambled to the user for them to guess it. My problem is that after one word the code just simply exits the loop. My intention is for the loop to be used again for a second and third time before exiting.
Here is the code:
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <string>
using namespace std;
int main() {
while (true) {
enum fields { KEY, HINT, Locked };
const int NUM_WORDS = 10;
const string WORDS[NUM_WORDS][Locked] = {
{"MITCHELL", "NICKNAME IS MITCH,SO WHAT IS MY NAME?"},
{"PIZZA", "MY FAVORITE FOOD, IS ITALY."},
{"ROYCE", "SOME TUMBLE AND SOME ROLLS...?"},
{"INFINITY", "THE IMAGINARY NUMBER IS?"},
{"AMY", "FAVORITE SONIC CHARACTER IS ?"},
{"FIAT", "CRYPTO OVER; THIS TYPE OF CURRENCY?"},
{"RUSSIA", "SAINT PETERSBURG IS IN ?"},
{"DONETELLO", "TEENAGE MUTANT NINJA TURTLES"},
{"SON", "BROOKLYN PEOPLE SAY THIS WORD"},
{"FUN", "FEELING HAPPY"}
};
srand(static_cast<unsigned int>(time(0)));
int choice = (rand() % NUM_WORDS);
string theWord = WORDS[choice][KEY]; // GUESSING THE WORDS
string theHint = WORDS[choice][HINT]; // Hint for Words
// Randomizing using the string; swapping charcters equal to the length of the words
string Jumble = theWord; // jumbled version of word
int length = Jumble.size();
for (int i = 0; i < length; ++i) {
int index1 = (rand() % length); // Random
int index2 = (rand() % length); // Random
char temp = Jumble[index1];
Jumble[index1] = Jumble[index2]; // Swapping charcters
Jumble[index2] = temp;
}
cout << "\t\t\Welcome to Word Jumble!\n\n"; // USING CARRIAGE RETURN; USING TITLE
cout << "Unscramble the letters to make a word.\n";
cout << "Enter 'hint' for a hint.\n";
cout << "Enter 'quit' to quit the game.\n\n";
cout << "The jumble is:" << Jumble;
string guess;
cout << "\n\nYour guess:";
cin >> guess;
while ((guess != theWord) && (guess != "quit")) {
if (guess == "hint") {
cout << theHint;
} else {
cout << "Sorry, that's not it.";
}
cout << "\n\nYour guess:";
cin >> guess;
}
if (guess == theWord) {
cout << "\nTHat's it! You guessed it!\n";
}
cout << "\nThanks for playing.\n";
return 0;
}
}

#include <cstdlib>
#include <ctime>
#include <iostream>
#include <string>
using namespace std;
int main() {
while (true) {
enum fields { KEY, HINT, Locked };
const int NUM_WORDS = 10;
const string WORDS[NUM_WORDS][Locked] = {
{"MITCHELL", "NICKNAME IS MITCH,SO WHAT IS MY NAME?"},
{"PIZZA", "MY FAVORITE FOOD, IS ITALY."},
{"ROYCE", "SOME TUMBLE AND SOME ROLLS...?"},
{"INFINITY", "THE IMAGINARY NUMBER IS?"},
{"AMY", "FAVORITE SONIC CHARACTER IS ?"},
{"FIAT", "CRYPTO OVER; THIS TYPE OF CURRENCY?"},
{"RUSSIA", "SAINT PETERSBURG IS IN ?"},
{"DONETELLO", "TEENAGE MUTANT NINJA TURTLES"},
{"SON", "BROOKLYN PEOPLE SAY THIS WORD"},
{"FUN", "FEELING HAPPY"}
};
srand(static_cast<unsigned int>(time(0)));
int choice = (rand() % NUM_WORDS);
string theWord = WORDS[choice][KEY]; // GUESSING THE WORDS
string theHint = WORDS[choice][HINT]; // Hint for Words
// Randomizing using the string; swapping charcters equal to the length of the words
string Jumble = theWord; // jumbled version of word
int length = Jumble.size();
for (int i = 0; i < length; ++i) {
int index1 = (rand() % length); // Random
int index2 = (rand() % length); // Random
char temp = Jumble[index1];
Jumble[index1] = Jumble[index2]; // Swapping charcters
Jumble[index2] = temp;
}
cout << "\t\t\Welcome to Word Jumble!\n\n"; // USING CARRIAGE RETURN; USING TITLE
cout << "Unscramble the letters to make a word.\n";
cout << "Enter 'hint' for a hint.\n";
cout << "Enter 'quit' to quit the game.\n\n";
cout << "The jumble is:" << Jumble;
string guess;
cout << "\n\nYour guess:";
cin >> guess;
while ((guess != theWord) && (guess != "quit")) {
if (guess == "hint") {
cout << theHint;
}
else {
cout << "Sorry, that's not it.";
}
cout << "\n\nYour guess:";
cin >> guess;
}
if (guess == theWord) {
cout << "\nTHat's it! You guessed it!\n";
}
cout << "\nThanks for playing.\n";
}
return 0;
}

You can use goto statement for what you are wanting to do, but before using it, we will ask the user if he/she want to play it again, we will take input, if he/she says yes(y) then we will restart the code, if no(n) then exit.
The final code:
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <string>
using namespace std;
int main() {
char res;;
x:
while (true) {
enum fields { KEY, HINT, Locked };
const int NUM_WORDS = 10;
const string WORDS[NUM_WORDS][Locked] = {
{"MITCHELL", "NICKNAME IS MITCH,SO WHAT IS MY NAME?"},
{"PIZZA", "MY FAVORITE FOOD, IS ITALY."},
{"ROYCE", "SOME TUMBLE AND SOME ROLLS...?"},
{"INFINITY", "THE IMAGINARY NUMBER IS?"},
{"AMY", "FAVORITE SONIC CHARACTER IS ?"},
{"FIAT", "CRYPTO OVER; THIS TYPE OF CURRENCY?"},
{"RUSSIA", "SAINT PETERSBURG IS IN ?"},
{"DONETELLO", "TEENAGE MUTANT NINJA TURTLES"},
{"SON", "BROOKLYN PEOPLE SAY THIS WORD"},
{"FUN", "FEELING HAPPY"}
};
srand(static_cast<unsigned int>(time(0)));
int choice = (rand() % NUM_WORDS);
string theWord = WORDS[choice][KEY]; // GUESSING THE WORDS
string theHint = WORDS[choice][HINT]; // Hint for Words
// Randomizing using the string; swapping charcters equal to the length of the words
string Jumble = theWord; // jumbled version of word
int length = Jumble.size();
for (int i = 0; i < length; ++i) {
int index1 = (rand() % length); // Random
int index2 = (rand() % length); // Random
char temp = Jumble[index1];
Jumble[index1] = Jumble[index2]; // Swapping charcters
Jumble[index2] = temp;
}
cout << "\t\t\Welcome to Word Jumble!\n\n"; // USING CARRIAGE RETURN; USING TITLE
cout << "Unscramble the letters to make a word.\n";
cout << "Enter 'hint' for a hint.\n";
cout << "Enter 'quit' to quit the game.\n\n";
cout << "The jumble is:" << Jumble;
string guess;
cout << "\n\nYour guess:";
cin >> guess;
while ((guess != theWord) && (guess != "quit")) {
if (guess == "hint") {
cout << theHint;
} else {
cout << "Sorry, that's not it.";
}
cout << "\n\nYour guess:";
cin >> guess;
}
if (guess == theWord) {
cout << "\nTHat's it! You guessed it!\n";
}
cout<<"Do you want to play again?(y/n)";
cin>>res;
if (res=='y'||'Y'){
goto x;
}
else{
cout << "\nThanks for playing.\n";
}
return 0;
}
}

Related

Check letters against the word of an arbitrary size in a Hangman game

Currently I am working on a hangman game, I had previously coded it to only work for a 5 letter word, but now would like to make it handle any length of word, how could I change this code to make it work how I want it to?
#include "stdafx.h"
#include <iostream>
#include <string>
#include <stdlib.h>
#include <cstdlib>
using namespace std;
int main()
{
string word;
int tries;
string guess;
string wordguess;
string output;
cout << "Enter a word for player two to guess: ";
cin >> word;
system("CLS");
cout.flush();
cout << "Guess the word!" << endl;
for (int i = 0; i < word.length(); i++)
{
cout << "_ ";
}
cout << "Enter a letter: ";
cin >> guess;
for (int tries = 5; tries > 0; tries--)
{
if (guess[0] == word[0]) {
output[0] = word[0];
cout << "You guessed the first letter! Good job!" << endl;
}
if (guess[0] == word[1]) {
output[2] = word[1];
cout << "You guessed the second letter! Good job!" << endl;
}
if (guess[0] == word[2]) {
output[4] = word[2];
cout << "You guessed the third letter! Good job!" << endl;
}
if (guess[0] == word[3]) {
output[6] = word[3];
cout << "You guessed the fourth letter! Good job!" << endl;
}
if (guess[0] == word[4]) {
output[8] = word[4];
cout << "You guessed the fifth letter! Good job!" << endl;
}
cout << output << endl;
cout << "You have " << tries << " tries left. Take a guess at the word: " << endl;
cin >> wordguess;
if (wordguess == word)
{
cout << "Congratulations, you guessed the word correctly!" << endl;
break;
}
}
system("pause");
return 0;
}
As you can tell I was checking each position from 0 to 4 (first through fifth letter). I know there are plenty of ways that I could have coded this better but as you can guess, I am new to coding and this is the way I thought of it. Please note this is still a work in progress so it is not fully complete. Any help would be great!
When designing an algorithm, think of how you would do this by hand, without a computer. Then let the code do the same.
If you were checking your friend's guess against a word written on sand, you would probably go about it like this:
go through the written pattern character by character, pronouncing your word in memory
for each letter, check if it is equal to the guess
if it is
replace the placeholder with it
memorize that your friend guessed right.
Also note if there are any placeholders left
if there aren't, your friend wins
finally, if your friend didn't guess right, score them a penalty point and check if they lose
Now, all that leaves is to put this down in C++. The language provides all sorts of entities - let's check which ones fit ours needs the best:
the word and the current pattern - strings of a fixed size
bits to memorize:
whether the current guess is right - bool
placeholders left - int
penalty points (or, equivalently, attempts left) - int
parts of the algorithm:
looping over a string - for loop of one of a few kinds
we need to replace the character in the pattern at the same index as the guessed letter in the word. So, we need to have the index when looping. Thus the flavor with the index variable, for(std::string::size_type i = 0; i < str.size(); ++i) probably fits the best.
// Example program
#include <iostream>
#include <string>
using namespace std;
class my_game
{
private:
string congrats_array[15] = {"first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "nineth", "tenth", "eleventh", "twelfth", "thirteenth", "fourteenth", "fifteenth"};
string word_to_guess;
int tries_left;
int word_length;
int letters_guessed_count;
string guessed_letters;
void check_letter(char letter);
void print_current_word_state();
public:
my_game();
void begin_the_game();
void play_the_game();
};
my_game::my_game()
{
}
void my_game::begin_the_game()
{
cout << "Enter a word for player to guess: " << endl;
cin >> word_to_guess;
system("CLS");
cout.flush();
cout << "Enter the tries amount!\n" << endl;
cin >> tries_left;
word_length = word_to_guess.size();
guessed_letters = "_";
letters_guessed_count = 0;
for(int i = 0; i < word_length - 1; i++){
guessed_letters += "_";
}
}
void my_game::play_the_game()
{
cout << "Guess the word!" << endl;
char letter;
for(int i = 0; i < tries_left; i++)
{
cout << guessed_letters << endl;
cout << "Enter a letter: " << endl;
cin >> letter;
check_letter(letter);
if(letters_guessed_count == word_length){
cout << "Congrats! You won!" << endl;
return;
}
}
cout << "You lose" << endl;
}
void my_game::check_letter(char letter)
{
for(int i = 0; i < word_length; i++)
{
if(word_to_guess[i] == letter && guessed_letters[i] != letter)
{
guessed_letters[i] = letter;
letters_guessed_count++;
cout << "You guessed the" << congrats_array[i] <<"letter! Good job!" << endl;
}
}
}
int main()
{
my_game game;
game.begin_the_game();
game.play_the_game();
}
So, in short what you need to do this with words of any arbitrary length is to use string's .substr() function and the stringstream library's .str() and << and >> operators. This version of your code uses a function that inserts a correctly guessed character at the appropriate indexed location. This will gradually replace the "_________" with letters at the correct places. This is much easier to do in Java, but stringstream is a good library I would highly recommend getting familiar with it. I'll leave the problem of how to handle multiple instances of a guessed character up to you (ie 'i' in "bibliography")
#include <string>
using std::string;
#include <sstream>
using std::stringstream;
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
string newString(string, int, string);
int main()
{
string word;
string guess;
int tries;
string output;
string input;
cout << "Enter word for player 2 to guess: ";
cin >> word;
stringstream ss;
//---------- fills the stream with "_"s matching the length of word
for(int i = 0; i < word.length(); i++)
ss << "_";
//----------- assigns the initial value of "___..." to output
ss >> output;
//----------- sets up the loop
tries = 5;
bool found = false;
for(int i = 0; i < 5; i++)
{
cout << "\nTry " << i << " of 5: Enter a letter or guess the word: ";
cin >> input;
if(input == word)
{
cout << "Congratulations, you guessed the word correctly!" << endl;
break;
}
//------------------ else, proceed with replacing letters
if(word.find(input) != std::string::npos)
{
size_t position = word.find(input); // finds index of first instance of the guessed letter
cout << "You guessed the " << position+1 << " letter! Good job!" << endl; // since strings start at index 0, position+1
//------- replaces appropriate "_" with the guessed letter
output = newString(input, position, output);
cout << "\n" << output;
// Around here you'll want to set up a way to deal with multiple instances
// of the same letter
}
else
cout << "Incorrect guess" << endl;
}
return 0;
}
//---------------------------------------------------
string newString(string guess, int index, string word)
{
string NewString;
stringstream temp;
//---------- hack up the string into sections before and after the index
string before = word.substr(0, index);
string after = word.substr(index+1, word.length() - index+1);
//---------------- populates the new stringstream and assigns it to the result
temp << before << guess << after;
NewString = temp.str();
return NewString;
}

C++ 'Word Jumble'

I have a small problem. I have attempted to make the game 'Word Jumble' with a scoring system. But sometimes, when the computer guesses a word, then it'll say: The word is: blank here. There should be a jumbled word there. When I try any word, it just subtracts 1.#INF points.
Code:
#include<iostream>
#include<string>
#include<stdlib.h>
#include<time.h>
using namespace std;
const int size=10;
string Words[size] = {
"consecutive",
"alternative",
"consequently",
"jumbled",
"computer",
"charger",
"food",//I'm hungry
"library",
"strawberry",
"carrier"
};
string Hints[size] = {
"Following continuously.",
"Something available as another opportunity.",
"As a result.",
"This word is rather jumbled, isn't it ;)",
"The enitiy you are reading this off of",
"My phone battery is running low",
"I'm hungry, I need some _",
"Where can I go get a book?",
"It's red, and not a berry."
"Either carries stuff, or is what your data company is called."
};
void main()
{
string word,hint;
double points=0;
bool correct=false,playAgain=true;
cout << "Welcome to Word Jumble!\n";
cout << "The objective of this game is to guess the jumbled word, correctly.\n";
cout << "Say 'quit' to quit, or 'hint' for a hint.\n";
while (playAgain==true)
{
correct = false;
int guesses = 0;
srand(static_cast<unsigned int>(time(0)));
int num = rand() % size + 1;
word = Words[num];
hint = Hints[num];
string jumble = word;
int length = jumble.size();
for (int i = 0; i < length*2; ++i)
{
int index1 = (rand() % length);
int index2 = (rand() % length);
char temp = jumble[index1];
jumble[index1] = jumble[index2];
jumble[index2] = temp;
}
cout << "The word is: " << jumble << endl;
double tempPoints=0;
while (correct==false)
{
string theGuess;
cout << "Guess the word: ";
cin >> theGuess;
guesses++;
while (!cin)
{
cin.sync();
cin.clear();
cout << "Ivalid entry, try again: ";
cin >> theGuess;
}
if (theGuess == word)
{
cout << "Correct! You guessed the word in only " << guesses << " tries!\n";
tempPoints += jumble.size()*1.5;
tempPoints -= (guesses - 1) / 4.0;
points += tempPoints;
cout << "You have been awarded " << tempPoints << " points this round for a total of " << points << "!\n";
correct = true;
cout << "Would you like to play again? (y or n): ";
char tempYN;
cin >> tempYN;
while (!cin || tempYN != 'y' && tempYN != 'n')
{
cin.sync();
cin.clear();
cout << "Invalid entry.\nWould you like to play again? (y or n): ";
cin >> tempYN;
}
if (tempYN == 'y')
{
playAgain = true;
}
else
{
playAgain = false;
}
}
else if (theGuess == "hint")
{
tempPoints -= (1.0 / (jumble.size())) * 40;
cout << "Hint: " << hint << endl;
correct = false;
playAgain = true;
}
else if (theGuess == "quit")
{
correct = true;
playAgain = false;
}
else
{
double sub = (1.0 / (jumble.size())) * 20;
cout << "Incorrect word, deducting "<<sub<<" points\n";
tempPoints -= sub;
playAgain = true;
correct = false;
}
};
};
cout << "Goodbye\n";
}
In the line:
int num = rand() % size + 1;
You are saying to select a random number between 0 and 9 then add 1.
If the random number is 9 the + 1 will make it 10. This means that you are trying to access a value in the array Words and Hints at index 10. Since arrays are 0 indexed and it's size is 10 that means you only have elements at 0 - 9.
You also will never get the first string in the arrays.

Program is not returning specified values?

I made a game where the player types in the scrambled word. Take for example, I have the word 'wall' which is then jumbled up to saying wlal. For a correct answer I multiply the length of the given word to the user by 1000, then report the score at the end.
However, I also have a hint feature set up, so when they type in hint they get a hint. As a penalty, I'd like it so the user get's their score cut in half. Also, if the player answers incorrectly, there is a 1000 point reduction to the score.
My program always sets the score to 0. What's the problem here.
EDITED CODE:
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <unistd.h>
using namespace std;
int main()
{
enum fields {WORD, HINT, NUM_FIELDS};
const int NUM_WORDS = 5;
const string WORDS[NUM_WORDS][NUM_FIELDS] = //5x2 array
{
{"wall", "Do you feel you're banging your head against something?"},
{"glasses", "These might help you see the answer."},
{"labored", "Going slowly, is it"},
{"persistent", "Keep at it."},
{"jumble", "It's what the game is all about."}
};
srand(static_cast<unsigned int>(time(0)));
int choice = rand() % NUM_WORDS;
//Choice value in array, than area in array where word and hint are
string theWord = WORDS[choice][WORD]; //word to guess
string theHint = WORDS[choice][HINT]; //hint for word
string jumble = theWord; //jumbled version of word
int length = jumble.size();
//Index1 and index2 are random locations in the string theWord
//last two lines swaps areas, ending the for function with a different
//jumble variable every time.
for (int i = 0; i < length; ++i)
{
int index1 = rand() % length;
int index2 = rand() % length;
char temp = jumble[index1];
jumble[index1] = jumble[index2];
jumble[index2] = temp;
}
cout << "\t\tWelcome to Word Jumble!\n\n";
cout << "Unscramble the letters to make a word.\n";
cout << "\n\n\nReady? (y/n)";
//I'm asking here if the player is ready
string isready;
cin >> isready;
if ((isready == "y") || (isready == "Y"))
{
cout << "Ok this is how the scoring works\n";
cout << "The length of the word you will guess is times by 5000.\n";
cout << "If you ask for a hint, your score will go down by half.\n";
cout << "If you get the wrong answer, your score will go down by 1000.";
cout << "\nOk, lets start!\n";
int counter = 3;
for(int i = 0; i < 3; ++i)
{
sleep(1);
cout << counter << "..." << endl;
counter--;
}
sleep(1);
}
else
{
cout << endl;
return 0;
}
cout << "Enter 'quit' to quit the game.\n";
cout << "Enter 'hint' for a hint.\n";
cout << "The jumble is: " << jumble;
//Score system
double score;
double amount_of_guesses, amount_of_wrong = 0;
string guess;
cout << "\n\nYour guess: ";
cin >> guess;
double wrong = 0;
while ((guess != theWord) && (guess != "quit"))
{
if (guess == "hint")
{
cout << theHint;
amount_of_guesses++;
}
else if (guess != theWord)
{
cout << "Sorry, that's not it.";
wrong++;
}
cout << "\n\nYour guess: ";
cin >> guess;
}
if (guess == theWord)
{
score = (theWord.length() * 1000);
}
if (amount_of_guesses != 0)
{
score = score / (amount_of_guesses * 2);
}
if( wrong != 0)
{
score = score - (wrong * 1000);
}
cout << "Your score is: " << score;
cout << "\nThanks for playing.\n";
return 0;
}
Your code works fine for me when double amount_of_guesses, amount_of_wrong = 0; is changed as: double amount_of_guesses=0; double amount_of_wrong = 0;
Additionally, the code score = score / (amount_of_guesses * 2); does not correctly penalize the player by cutting his or her score in half each time they ask for a hint.
You could replace that line with the following code segment to correctly penalize by cutting the score in half every time:
if (amount_of_guesses != 0)
{ while(amount_of_guesses!=0)
{
score = (score / 2);
amount_of_guesses--;
}
}
The code
int amount_of_guesses, amount_of_wrong = 0;
does not initialize amount_of_guesses to 0. It is likely to be a huge number since it will be what is in memory when program is running. If score is lower than amount_of_guesses, result will be 0 using integer division.
I believe the issue is that you never initialize amount_of_guesses. This declaration
int amount_of_guesses, amount_of_wrong = 0;
initializes amount_of_wrong to 0, but amount_of_guesses will just hold some random value that depends on what happens to be in memory. If that's a large value, then this:
if (amount_of_guesses != 0)
{
score = score / (amount_of_guesses * 2);
}
will end up making score == 0 (note that since score is an integer score / (amount_of_guesses * 2) ends up being the floor of that division)

C++ - Replacing "_" with a character

Using C++, I'm trying to make a hangman game to become better at using C++ and programming in general. Anyways, the issue I'm facing is that I'm not sure how to replace the dashes within a string with the letter the user has guessed.
I think my problem is with the fact the word chosen is randomly chosen from an array and I'm not sure how to go about finding the positions within the randomly chosen string which consists of the guessed character.
I have commented out the area that's causing the issue.
#include <iostream>
#include <array>
#include <string>
#include <stdlib.h>
#include <time.h>
#include <cstddef>
#include <algorithm>
using namespace std;
int main()
{
string words[3] = {"stack", "visual", "windows"};
string guess;
cout << "Welcome to hangman.\n";
cout << "\n";
srand(time(NULL));
int RandIndex = rand() % 3;
string selected = words[RandIndex];
for (int i = 1; i <= selected.size(); i++) {
cout << "_ ";
}
cout << "\n";
cout << "\nType in a letter: ";
cin >> guess;
cout << "\n";
if (selected.find(guess) != string::npos) {
/*for (int i = 1; i <= selected.size(); i++) {
if (selected.find(guess) != string::npos) {
cout << "_ ";
} else {
cout << guess << " ";
}
}*/
} else {
cout << "\nNay!\n";
cout << "\n";
}
cout << "\n";
cout << "\n";
system("PAUSE");
return 0;
}
I was thinking about using the replace() function but the problem I face here is that I'm not replacing the string within selected variable but sort of iterating through the word itself, if that made any sense whatsoever?
Use a second string, that is initialized with the underscores. If the find function doesn't return string::npos it returns the position in the string, and this is the same position you should change in the string with the underscores as well.
You actually need to use a second string to store the "guessed" string; this is because you need to keep track of all the guessed letters and display them.
something like :
string s ="test";
string t=""; //empty string
for(int i=0;i<s.size();i++)
t.append("_"); //initialize the guess string
cout<<t<<'\n';
char c;
cin >> c;
int pos = s.find(c); //get the first occurrence of the entered char
while(pos!=-1) //look for all occurrences and replaced them in the guess string
{
t.replace(pos,1,1,c);
pos = s.find(c, pos+1);
}
I think you need to maintain some extra state while looping - to keep track of which letters have / haven't been guessed.
You could add a new string current_state which is initially set to the same length as the word but all underscores. Then, when the player guesses a letter, you find all instances of that letter in the original word, and replace the underscore with the letter guessed, at all the positions found but in current_state.
First i would initialize a new string to show the hidden word:
string stringToDisplay = string( selected.length(), '_');
Then For each letter given by the user i would loop like this:
(assuming guess is letter)
size_t searchInitPos = 0;
size_t found = selected.find(guess, searchInitPos));
if (found == string::npos)
{
cout << "\nNay!\n";
cout << "\n";
}
while( found != string::npos)
{
stringToDisplay[found] = guess;
searchInitPos = found+1;
found = selected.find(guess, searchInitPos));
}
cout << stringToDisplay;
Hope this will help
I think it should be that:
string words[3] = {"stack", "visual", "windows"};
char guess;
string display;
cout << "Welcome to hangman.\n";
cout << "\n";
srand(time(NULL));
int RandIndex = rand() % 3;
string selected = words[RandIndex];
for (int i = 0; i < selected.size(); i++) {
display.insert(0, "_ ");
}
cout << display;
while(display.find("_ ") != string::npos) {
cout << "\n";
cout << "\nType in a letter: ";
cin >> guess;
cout << "\n";
bool flag = false;
for (int i = 0; i < selected.size(); i++) {
if (selected[i] == guess) {
display.replace(i*2, 1, 1, guess);
flag = true;
}
}
if (!flag) {
cout << "\nNay!\n";
cout << "\n";
} else {
cout << display;
}
}

Logic error, assistance required

I am encountering a logical error with this app. It is a word jumble app that displays a jumbled word and asks the player if he/she would like to play again once they guess correctly.
When I tell the app I do not want to play again it continues through the sequence anyway. I have a feeling that its bad nesting on my part.
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
enum fields {WORD, HINT, NUM_FIELDS};
const int NUM_WORDS = 5;
const string WORDS[NUM_WORDS][NUM_FIELDS] =
{
{"wall", "Are you banging your head against something?"},
{"jumble", "Its what this game is all about."},
{"glasses", "You might need these to read this text."},
{"labored", "Going slowly, is it?"},
{"persistent", "Keep at it."},
};
srand(static_cast<unsigned int>(time(0)));
cout << "\t\tWelcome to Word Jumble!\n\n";
cout << "Unscramble the the letters to make the word!\n";
cout << "Enter 'hint' for a hint\n";
cout << "Enter 'quit' to quit the game\n\n";
const int MAX_LEVEL = NUM_WORDS - 1;
int totalScore = 0;
for (int level = 0; level <= MAX_LEVEL; ++level)
{
string theWord = WORDS[level][WORD]; // Word to guess
string theHint = WORDS[level][HINT]; // Word hint
char playAgain;
string jumble = theWord; //Jumbled version of the word
int length = jumble.size();
int score = jumble.size() * 10;
for (int i = 0; i < length; ++i)
{
int index1 = (rand() % length);
int index2 = (rand() % length);
char temp = jumble[index1];
jumble[index1] = jumble[index2];
jumble[index2] = temp;
}
cout << jumble << endl;
string guess;
cout << "\nYour Guess: ";
cin >> guess;
while ((guess != theWord) && (guess != "quit"))
{
if (guess == "hint")
{
cout << theHint;
score = score / 2;
}
else
{
cout << "\n\nSorry thats not it.\n\n";
}
cout << "\n\nYour Guess: \n\n";
cin >> guess;
}
if (guess == theWord)
{
cout << "Thats it! You guessed it!\tYou scored: " << score << "\n\n";
cout << "Would you like to play again? (y/n): ";
cin >> playAgain;
if (playAgain = 'y')
{
continue;
}
else if (playAgain = 'n')
{
cout << "Your total score is: " << totalScore << endl;
break;
}
}
else if (guess == "quit")
{
if (totalScore > 0)
{
cout << "Your total score is: " << totalScore << endl;
}
break;
}
}
cout << "\nGoodbye.";
return 0;
}
When comparing playAgain to 'y' and 'n', you only have one equals sign, causing the first one ('y') to always execute instead of it being an actual choice, since the value of 'y' is not 0.
To fix this, they should be:
if (playAgain == 'y') //note ==
{
continue;
}
else if (playAgain == 'n') //note ==
{
cout << "Your total score is: " << totalScore << endl;
break;
}
Also, any sane (more modern) compiler should warn you about this if you have warnings turned on. Be sure to turn those on and take heed of them.
I think you will need == for your playAgain question. I often make mistakes with that.