What is wrong with my do...while logic, and continue logic? - c++

I'm new to stackoverflow, and also somewhat new to programming, so please don't mind my poor formatting of the code. I have two problems with my code.
My continue statement, which I'm using to continue the loop if the player types 'y' or 'Y', doesn't work. It terminates the program after only getting the guess correctly, which leads me to:
2.My continue counter goes past 0 without stopping, and I just can't see my error in the logic of the program.
I can't see the problems with my logic.
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <ctime>
#include <random>
using namespace std;
int getNumber(); //random number prototype
double getScore(); //gets score
int chances = 7; //chances to guess with
int main()
{
int guess = 0,
random;
char retry = 'y'; //initialize retry to 'y'
cout << "This is a random number guessing game. " << "You will be guessing between 1-100."
<< "You have 7 chances. Good luck! \n \n" << endl;
random = getNumber(); //give the function a variable
do
{
cout << random << "\n" << "\n";
chances--;
cout << "Enter your guess: ";
cin >> guess;
if (guess == random)
{
cout << "You have won the game! " << "Your score was: " << getScore();
cout << "Would you like to retry? (Y or N): ";
cin >> retry;
if (retry == 'y' || retry == 'Y')
{
chances = 7;
guess = 0;
getNumber();
continue; //player can retry the game
}
else if (chances == 0)
{
cout << "You have no chances left. Retry? (Y or N): ";
cin >> retry;
if (retry == 'y' || retry == 'Y')
{
chances = 7;
guess = 0;
getNumber();
continue;
}
}
return 0;
}
else if (guess != random)
cout << "You got it wrong. \n" << "You have: " << chances << " chances left" << endl << endl;
else
cout << "Incorrect Input. Please type a number." << endl << endl;
} while (guess != random);
return 0;
}
int getNumber()
{
unsigned seed = time(0); //seed the random number
srand(seed);
int randNum = rand() % 10 + 1; //random number in the range of 1-10
return randNum;
}

if (retry == 'y' || 'Y')
This is incorrect logic, which is why your code does not work the way you want it to. You want it to be:
if (retry == 'y' || retry == 'Y')
Fix this logic error in your other if-else statements as well.

You'll wanna take a look at this
Your continue statement is jumping to the end and checking the condition, guess != random, which evaluates to false and exits the do while. What you need to do is reset guess to a value such as 0 so that the condition does evaluate to true.

Related

How to prompt user to re-loop the whole program?

I want the user to choose between playing the game again or ending the program, however when prompted, if they press 'y' the same thing gets repeated over and over instead of the whole program from the very beginning. I've tried while loops, do/while loops, if statements, rearranging the code, but nothing has worked. Any advice?
#include <iostream>
#include <string>
using namespace std;
int main(){
string animal = "fish";
string guess;
char choose = 'Y' ;
int count = 0;//keeps a running total of how many times the user
has guessed an answer.
int limit = 5;//allows user to guess only 5 times, otherwise
they loose the game.
bool out_of_guesses = false;//to check whether the user has run
out of guesses.
cout << "I am thinking of an animal.\n" << endl;
do{
while(animal != guess && !out_of_guesses){//Nested while
loop inside main loop to keep track of how many tries the user has
attempted and to validate their answers.
if(count < limit){
cout << "Can you guess what animal I am thinking of?: ";
getline(cin, guess);
count++;
if(animal != guess){
cout << "\nHmm, nope. That's not the animal I'm
thinking of." << endl;
if(count > 2 && count <5){
cout << "I'll give you a hint. It lives in
water." << endl;
}
}
}
else{
out_of_guesses = true;
}
}//End nested while loop
if(out_of_guesses){
cout << "\nI'm sorry, but you are out of guesses." <<
endl;
}
else{
cout << "\n*** Good job! You guessed the correct animal!
***" << endl;
cout << "\t\t><)))º> ❤ <º)))><\t\t" << endl;
}
//The do-while loop is there to ask the user if they wish to
play the game again.
cout << "Would you like to try again?(y/n): ";
cin >> choose;
if(choose == 'N' || choose == 'n')
break;
}while(choose == 'Y' || choose == 'y');
return 0;
}
The bool out_of_guesses = false; must be in-between while(true) and while(animal != guess && !out_of_guesses), and not outside the first while loop. Because our while loop condition is always false, and then it does enter it.
You should also reset your guess variable in-between those 2 loops, else same thing could happen (false while loop) in case of the answer is found.
Here the code with some refactoring/review, which I used the guess as upper case to handle any typography of the answer. I also removed the out of guess variable to use the count and limit one instead.
#include <iostream>
#include <string>
#include <cctype>
int main()
{
const std::string animal = "FISH";
const int limit = 5;
do
{
std::cout << "I am thinking of an animal.\n";
int count = 0;
std::string guess;
while(animal.compare(std::toupper(guess)) != 0 && count < limit)
{
std::cout << "Can you guess what animal I am thinking of?: \n";
std::cin >> guess;
count++;
if(animal.compare(std::toupper(guess)) != 0)
{
std::cout << "\nHmm, nope. That's not the animal I'm thinking of.\n";
if(count > 2)
{
std::cout << "I'll give you a hint. It lives in water.\n";
}
}
}
}//End nested while loop
if(count >= limit)
{
std::cout << "\nI'm sorry, but you are out of guesses.\n";
}
else
{
std::cout << "\n*** Good job! You guessed the correct animal! ***\n";
std::cout << "\t\t><)))º> ❤ <º)))><\t\t\n";
}
char choose = 'Y' ;
std::cout << "Would you like to try again?(y/n): ";
std::cin >> choose;
if(std::toupper(choose) == 'N') break;
} while(true);
return 0;
}

How to evaluate number greater than and less than in the same while loop?

// DiceRollProject.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <time.h>
using namespace std;
int diceRoll(int max); // function definition
int getValidInteger();// function definition
int main() {
srand(time(0)); // seed the random number generator
int exitProgram = 0;
int guess, rollValue;
int maxRollValue = 6;
cout << "Hello! Let's play a dice game. Let me do the first roll for you.\n" << endl;
rollValue = diceRoll(maxRollValue);
cout << "In this roll, you got: " << rollValue << "\n" << endl;
do {
rollValue = diceRoll(maxRollValue);
cout << "What's your guess for the next roll? Enter an integer between 1 and " << maxRollValue << ": ";
guess = getValidInteger();
// TODO: Validate input
if (guess > rollValue)
{
cout << "The guess was too high!";
}
if (guess < rollValue)
{
cout << "The guess was too low!";
}
if (guess == rollValue)
{
cout << "You guessed correctly, congrats!";
}
cout << "In this roll, you got: " << rollValue << "\n" << endl;
// TODO: Evaluate result
cout << "Enter 1 to exit or any other integer to continue rolling ";
exitProgram = getValidInteger();
cout << "\n";
if (exitProgram == 1)
{
cout << "Sorry to see you go. Have a wonderful day!\n" << endl;
}
} while (exitProgram != 1);
return 0;
}
// Roll the die
int diceRoll(int max) {
int rollValue;
rollValue = (rand() % max) + 1;
return rollValue;
}
// Check if user entered an integer
int getValidInteger() {
int userInput;
cin >> userInput;
while (userInput < 1) {
if (userInput < 1)
{
cout << "Please enter a number greater than or equal to 1\n";
}
if (userInput > 6)
{
cout << "Please enter a number less than or equal to 6\n";
}
}
if (cin.fail()) {
cin.clear();
cin.ignore();
cout << "Please enter an Integer only ";
cin >> userInput;
cout << "\n";
}
return userInput;
}
I have a dice roll guessing game, I'm trying to evaluate the users input, to make sure that they can't enter a number less than 1 and greater than 6, unfortunately, with just my if statements, they can still enter these numbers, although a string is displayed that the input is not valid, I want to make a while loop that keeps asking them to enter a valid number equal or greater than 1 and equal to and less than 6, if the user keeps inputting an incorrect number, the while loop will keep asking them for a valid number, until they do enter one, which will then run the program as normally.
First of all, inside the while loop you have dead code.
while (userInput < 1) {
if (userInput < 1)
{
cout << "Please enter a number greater than or equal to 1\n";
}
if (userInput > 6)
{
cout << "Please enter a number less than or equal to 6\n";
}
}
Within the loop body, the first if is always true and the second one is always false. You should enter in a loop when the user writes an invalid input. This happens when (userInput < 1 or userInput > 6)
After the evaluation of the while's condition, you should ask the user to write input
do {
cout << "Please enter an Integer only ";
cin >> userInput;
if (userInput < 1)
{
cout << "Please enter a number greater than or equal to 1\n";
}
if (userInput > 6)
{
cout << "Please enter a number less than or equal to 6\n";
}
}while(userInput < 1 || userInput > 6);
So your condition that will keep you in the while loop is if the person guesses too high or too low. Inside the while loop I would add the updating condition or statement that you would like to repeat. So in your case, "your guess is too high" or " your guess is too low" and ask for their input again. I am not a pro but I would keep it simple by constructing 2 while loops, one for too high and one for too low just like your if statements. literally you can just change your first two if statements to while loops and adding an few extra lines of cout to ask the person to guess again and validate their input. I hope this helped.
from what I've understood you are looking for something like this:
int main (){
int my_magic_number=(rand()%6)+1,usernumber=-1;
bool state;
while (usernumber!=my_magic_number){
cin>>usernumber;
state = (usernumber<1||usernumber>6);
while (state) {
cout<<"You entered a number outside the range [1,6] please try again\n";}
cin>>usernumber;
state = (usernumber<1||usernumber>6);
}
if (usernumber!=my_magic_number) {/* do whatever you want */}
} //while loop
} // main

Simplify code for an in-class demo

For a technical writing class I will be leading and having the rest of the class (on the school computers with Visual Studio 2013) participate in making a a simple guess game program. I am trying to make it as straight forward as possible and easy to understand as many of my classmates are not programmers.
Is there anything I can make simpler or easier to follow?
using namespace std;
int main(){
char response = 'y';
while (response != 'n'){
srand(time(NULL));
int guess = -1;
int answer = (rand() % 100) + 1;
while (guess != 0){
cout << "Guess a number between 1 and 100. Guess 0 to quit game." << endl;
cin >> guess;
if (guess == 0){
break;
}
else if (guess == answer){
cout << "Correct!" << endl;
break;
}
else if (guess < answer){
cout << "Too low, guess again!" << endl;
}
else {
cout << "Too high, guess again!" << endl;
}
}
cout << "Play again? (y/n): ";
cin >> response;
}
}
Consider dropping the "play again" or drop the "Guess 0 to quit". In fact, drop the "quit" because the Ctrl-C or close-button of the terminal are already there.
Rename answer to something less confusing (pick or secret) and make it const.
Extract a function for the "voodoo" to generate a random number. Makes it more legible!
Turn the while into a do {} while so you don't have this unintuitive check response != 'n' before anything ever happened at all!
Same for while(guess!=0). Except, you can lose the redundant condition altogether. You already had break there...
Lose the else if where break already made the branch redundant.
Make a polite comment about missing error handling... So people don't sue you when their programs runs haywire :)
Also, write it incrementally, so do e.g.
#include <iostream>
using namespace std;
void play_round();
int main() {
srand(time(NULL));
char response;
do {
play_round();
cout << "Play again? (y/n): ";
cin >> response;
} while (response != 'n');
}
int pick_random(int from, int to) {
return (rand() % (to-from+1)) + from;
}
void play_round() {
const int secret = pick_random(1, 100);
do {
cout << "Guess a number between 1 and 100: ";
int guess;
cin >> guess;
if (guess == secret) {
cout << "Correct!" << endl;
break;
}
} while (true);
}
And then elaborate adding
if (guess == 0) {
break;
}
And eventually
if (guess < secret) {
cout << "Too low, guess again!" << endl;
}
if (guess > secret) {
cout << "Too high, guess again!" << endl;
}
Note how the branches are independent!
Optionally elaborate, doing:
int pick_random(int from, int to) {
return (rand() % (to-from+1)) + from;
}
and use pick_random(1, 100) etc :)

Simple Number Guessing Game. C++

I've been trying to make a simple game where the computer generates a random number and you try to guess it. It also stores the amount of guesses you make "tries".
However, when I run the program, it simply prints: "Let's play a game. I'll think of a number 1-100. Try to guess it."
Here's my code:
#include <iostream>
int main()
{
using namespace std;
int the_number;
int guess;
int tries;
the_number = rand() % 101 + 1;
cout << "Let's play a game!";
cout << "I will think of a number 1-100. Try to guess it.";
cout << endl;
cin >> guess;
for (tries = 0; tries++;)
{
if (guess == the_number)
{
cout << "You guessed it!";
cout << "And it only took you: " << tries;
}
else if (guess < the_number)
{
cout << "Higher";
tries++;
}
else if (guess > the_number)
{
cout << "Lower";
tries++;
}
else
cout << "That's not even in range!";
return 0;
}
}
I don't understand why this doesn't work, could someone explain why not?
The reason your program does not print anything after "Let's play a game. I'll think of a number 1-100. Try to guess it." is the way you have written your for loop.
for ( tries = 0; tries++; )
breaks out of the loop without doing anything because tries++ evaluates to 0.
Also, for your program to work correctly, you need to add more code to read guesses. Something like the code below, should work.
for (tries = 0; ; tries++)
{
if (guess == the_number)
{
cout << "You guessed it!";
cout << "And it only took you " << tries << " tries.\n";
break;
}
else if (guess < the_number)
{
cout << "Higher";
cin >> guess;
}
else if (guess > the_number)
{
cout << "Lower";
cin >> guess;
}
}
You can define a couple of variables that will make your code more understandable, something like this :
#include <iostream>
using namespace std;
int main()
{char EndGame = 'N';
int MyNumber = 150 , playerguess;
cout << "I have a number between 1 and 100.\nCan you guess my number ??\nPlease type your first guess.\n?" << endl;
do{
cin >> playerguess;
if (playerguess > MyNumber) {
cout << " Too High. Try again." << endl;
}
else if (playerguess == MyNumber) {
cout << "Excellent ! You Got It ! \n If you want to exit press Y" << endl;
cin >> EndGame;
break;
}
else {
cout << " Too Low. Try again." << endl;
}
} while (1);
return 0;
}
This will make the number equal to 150. Each time the user inputs a value, the console will determine whether it is higher, lower or equal to the number.
If you want instead to make it a random number each time, you can simply use the <random> library and use the module operator with a number like 100 or 101. Then, you can add 1; this will generate only positive integers.
You should use while loop here, not for:
while (the_number != guess)
{
//
//
}
And try using the new <random> header instead of rand() function:
#include <random>
std::random_device rd;
std::default_random_engine engine(rd());
std::uniform_int_distribution<int> uniform_dist(1, 100);
the_number = uniform_dist(engine);
Your for loop is wrong (it needs 3 things: initialization, check condition and the todo step after each loop.
For example:
for (tries = 0; tries < 5; tries++)
Also you loop the guessing part, but you forget to ask the user for a new number. I would suggest to move the cin << guess into the for loop.

while loop acting up... not doing what it should for some reason

I have this code for a simple Dice throwing program with betting units and everything... you bet, if you get it right you get the amount u bet times the amount of dice you chose... if you're wrong but by a little (in the range of the number you picked +- the number of dice u picked) you don't lose anything, and if you're really off you lose...
I have a while loop that basically keeps 2 things in mind: as long as the user either has BUs or if they didn't type "no" or "No" for the try again... but for some reason it just doesn't work... lol. any ideas why? the betting system works, it recognizes that betting.currentBU == 0, but the while loop just won't react lol.
#include <iostream>
#include <string>
#include <cstdlib>
#include <time.h>
#include <limits>
using namespace std;
struct Dices{ // structure containing all the dice related integers
int dice;
int total;
int choice;
} Dices = {0,0,0};
struct betting{ // structure containing all the betting integers
int currentBU;
int bettedBU;
} betting = {100, 0};
int DiceThrow(int dicechoice, int totalnum){ // a method for the dice being rolled
for(int i=1; i <= dicechoice;i++){
totalnum = totalnum + (rand() % 6 + 1); //total number, repeated by the loop for every dice
}
return totalnum;
}
int winningbet(int dicea, int cBU, int bBU){ // in case the user guesses it right
std::cout << "Congratulations, you got it right! \n";
cBU = cBU + (dicea * bBU); // give him money...
return(cBU);
}
int losingbet(int dicen, int totaln, int choicen, int cBU2, int bBU2){ //in case the user guesses wrong
if(choicen > (totaln+dicen) || choicen < (totaln+dicen)) // checks how wrong he is, if he's too off, he loses BUs
cBU2 = cBU2-bBU2;
else
std::cout << "you we're so close, you don't lose any BUs! \n"; //if he was really close, just let him know he was close
return(cBU2);
}
int main(){
string decision; // decision if they want to keep playing or not
srand ( (unsigned int)time(NULL) );
while(decision != "no" || decision != "No" || betting.currentBU != 0) // makes sure of the decision AND that he still has BUs
{
Dices.total = 0;
std::cout << "how many dice would you like to use? ";
std::cin >> Dices.dice;
std::cout << "how many How many BUs are you betting?(" << betting.currentBU << " BUs left) ";
std::cin >> betting.bettedBU;
if(betting.bettedBU > betting.currentBU){ // if he doesn't have enough BUs
std::cout << "Sorry, you don't have that many BUs...";
std::cout << "Want to try again with a different amount?(Yes/No) ";
std::cin >> decision;
}
else{
std::cout << "guess what number was thrown: ";
std::cin >> Dices.choice;
Dices.total = DiceThrow(Dices.dice, Dices.total);
if(Dices.choice == Dices.total){
betting.currentBU = winningbet(Dices.dice, betting.currentBU, betting.bettedBU);
std::cout << "Want to try again?(Yes/No) ";
std::cin >> decision;
} else{
std::cout << "Sorry, the number was " << Dices.total << "... better luck next time \n" ;
betting.currentBU = losingbet(Dices.dice, Dices.total, Dices.choice, betting.currentBU, betting.bettedBU);
if(betting.currentBU > 0){
std::cout << "Want to try again?(Yes/No) ";
std::cin >> decision;
}
}
}
}
if(betting.currentBU == 0){
std:cout << "sorry, you ran out of BUs...";
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
}
else{
std::cout << "your final BU count is: " << betting.currentBU << "\n";
std::cout << "Thanks for playing, see you next time! (Press ENTER to terminate...)";
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
}
return 0;
}
isn't it supposed to be:
while(decision != "no" && decision != "No" && betting.currentBU != 0)
We need to check if decision not equal to "no" AND not equal to "No" AND the currentBU not equal to 0
Your test is while (A || B || C), which will loop as long as ANY of those three things are true. Since decision can't be equal to both "no" and "No" at the same time, at least one of those two not-equals tests will always be true, so the loop will loop forever...