Hello, I'm new to programming and trying a program that You need to guess the name of a video game character, there are only 3 guesses if you ran out of guesses you will lose. I used a do-while loop here so I can do it again and again... The problem here is that every time The loop starts again It displays the prompt 2 times even though It's supposed to be 1 time prompt per guess but it displays 2 prompt. Can you please help me maybe I'm doing the algorithm wrong, Thanks!
int guessCount = 0;
int guessLimit = 3;
bool outofGuesses = false;
Try putting these before the do {. Everytime through the loop you are resetting these values to their initial condition. Also secretWord can be moved to before the do{ as well - as it only needs to be initialised once.
You are mixing std::getline and std::cin. std::getline retrieves (and removes) all the characters in the stream, including the enter character. std::cin leaves the enter character in the stream to be extracted with std::getline when the do loop repeats. You need to ignore (remove) the remaining characters in the stream after using std::cin.
#include <iostream>
#include <string>
#include <cctype> // ::tolower
#include <limits> // numeric_limits
int main()
{
char rerun_option { 'n' };
do
{
std::string secretWord { "Arthur Morgan" };
std::string guess { };
int guessCount { };
int guessLimit { 3 };
bool outofGuesses { false };
while (secretWord != guess && !outofGuesses)
{
if (guessCount < guessLimit)
{
std::cout << "Enter video game character name guess: ";
std::getline(std::cin, guess);
guessCount++;
}
else
{
outofGuesses = true;
}
}
if (outofGuesses)
{
std::cout << "\nYou Lose!\n\n";
outofGuesses = false;
}
else
{
std::cout << "\n*** You Win! ***\n\n";
}
std::cout << "Try Again?(Y/N) ";
std::cin >> rerun_option;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // clear the input stream
std::cout << '\n';
}
while (::tolower(rerun_option) == 'y');
}
Enter video game character name guess: a
Enter video game character name guess: b
Enter video game character name guess: c
You Lose!
Try Again?(Y/N) y
Enter video game character name guess: d
Enter video game character name guess: Arthur Morgan
*** You Win! ***
Try Again?(Y/N) n
There are very good reasons why the C++ standard introduced namespaces, take advantage of those reasons. Saving a couple of keystrokes is not worth the hassles when names clash.
After a while always typing std:: will become almost automatic.
So, yes, I would recommend you never have usingnamespace std; in your code, always type the namespace identifier.
I don't even recommend using using std::cout;, using std::cin;, etc.
For me having the namespace identifier prefix instantly identifies what library I'm using. Makes the code easier to read.
different styles... I prefer using std::cout; and similar. I find std:: on everything to be visual clutter. I use namespace std for short programs, eg samples on this site, as well, even though its not 'professional'.