Write a program that continues to ask the user to enter any number other than 5 until the user enters the number 5.
Then tell the user "Hey! you weren't supposed to enter 5!" and exit the program.
★ Modify the program so that after 10 iterations if the user still hasn't entered 5 will tell the user "Wow, you're more patient then I am, you win." and exit.
★★ Modify the program so that it asks the user to enter any number other than the number equal to the number of times they've been asked to enter a number. (i.e on the first iteration "Please enter any number other than 0" and on the second iteration "Please enter any number other than 1"m etc. etc. The program must behave accordingly exiting when the user enters the number they were asked not to.)
I got most of the program to work. I have it to a point where it asks for a number starting at 0 and going up, it gives the user the patient message after 10 tries, and exits the program if they enter the number they are not supposed to. However if the user inputs the number above what it tells you not to enter, the program exits with no message.
I do not really know what to search to fix this issue. I have however tried to move some things around, and got rid of some redundant variables.
Any hints would be appreciated, please do not give me the answer up front! Here's what I have so far.
#include <iostream>
int main()
{
const int GUESS = 1; // constant for number of tries
const int PATIENCE = 10; // constant for message at 10 tries
int UserNum; // player input
int InputNum = GUESS; // intializes GuessNumber
// asks for player input
do
{
std::cout << "Enter any number other then "<< InputNum << ": ";
std::cin >> UserNum;
// exits program if user inputs the number displayed
if (UserNum == InputNum)
{
std::cout << "Hey! you weren't supposed to enter " << InputNum << "!\n";
}
// increase the Guess counter if they dont enter the number displayed
else if (UserNum != InputNum)
{
InputNum++;
}
if (InputNum == PATIENCE)
{
std::cout << "Wow, you're more patient then I am, you win.\n";
break;
}
} while (UserNum != InputNum);
return 0;
}
your problem is in do while loop condition
statements are executed first and condition are checked later
for example
InputNum is initialized as 1
so if you enter 2 as input for UserNum , in the else if condition ,InputNum will be incremented to 2
when this condition is evaluated
while (UserNum != InputNum)
it will be false as 2==2
loop breaks
solution
change PATIENCE = 11 and use
while (1)
// this will run infinitely but it will break after 10 iteration or when u press the same number which u shouldn't
instead of
while (UserNum != InputNum)
the full program
#include <iostream>
int main()
{
const int GUESS = 1; // constant for number of tries
const int PATIENCE = 11; // constant for message at 10 tries
int UserNum; // player input
int InputNum = GUESS; // intializes GuessNumber
// asks for player input
do
{
std::cout << "Enter any number other then " << InputNum << ": ";
std::cin >> UserNum;
// exits program if user inputs the number displayed
if (UserNum == InputNum)
{
std::cout << "Hey! you weren't supposed to enter " << InputNum << "!\n";
break;
}
// increase the Guess counter if they dont enter the number displayed
else if (UserNum != InputNum)
{
InputNum++;
}
if (InputNum == PATIENCE)
{
std::cout << "Wow, you're more patient then I am, you win.\n";
break;
}
} while (1);
system("pause");
return 0;
}
Hey try this program it does exactly what you want.
#include <iostream>
int main ()
{
int GUESS = -1; //loop variable
const int PATIENCE = 10; // constant for message at 10 tries
int InputNum; // input from user
std::cout << "PATIENCE Test" << "!\n";
do
{
GUESS++;
// asks for player's input
std::cout << "Enter any number other than " << GUESS << ": ";
std::cin >> InputNum;
// exits program if user inputs the number displayed
if (GUESS == InputNum)
{
std::
cout << "Hey! you weren't supposed to enter " << GUESS << "!\n";
break;
}
if (GUESS == PATIENCE)
{
std::cout << "Wow, you're more patient then I am, you win.\n";
break;
}
}
while (GUESS != InputNum);
return 0;
}
Related
On c++, im trying to make a program that will repeatedly accept the input of the user unless -999 is pressed. Additionally, if the input is not divisible by 5 or 20, then I asked for it to output "must enter divisible by 5 or 20." I want this to continue being done until they enter -999 but I do not know where to put my while loop or what to put if it is not entered. I also do not know where to put the "when finished enter -999 to leave" while making it eligible for all times and not just the start. Thank you!!!
#include <iostream>
using namespace std;
int main(void)
{
int amountEntered;
cout << "Please enter the amount of money you would like to dispense (must be in 20's or 5's)" << endl;
cout << "when finished, enter -999 to leave" << endl;
if (amountEntered == -999)
{
cout << "Thank you for doing business." << endl;
}
cin >> amountEntered;
if (amountEntered % 20 == 0)
{
cout << amountEntered / 20 << endl;
}
else
{
if (amountEntered % 5 == 0)
{
cout << amountEntered / 5 << endl;
}
else
{
cout << "You must enter multiples of twenty or five only!" << endl;
}
}
{
while (amountEntered != -999);
while (amountEntered % 5 == 0);
else
{
if (amountEntered % 5 != 0)
{
cout << "You must enter multiples of twenty or five only!" << endl;
}
}
while (amountEntered % 20 == 0);
}
if (amountEntered % 20 != 0);
{
cout << "You must enter a number divisible by 20 or 5!" << endl;
}
if (amountEntered = -999)
{
cout << "Thank you for doing business." << endl;
}
}
Here is some pseudocode to illustrate:
while true
get input
if input is -999 (or other conditions)
break out of loop
else
// rest of code goes here
So basically, wrap the whole thing in a while true loop and then use the conditional logic to break out of the loop when certain conditions are met.
On c++, im trying to make a program that will repeatedly accept the input of the user unless - 999 is pressed.
Additionally, if the input is not divisible by 5 or 20, then I asked for it to output "must enter divisible by 5 or 20."
#include <limits> // std::numeric_limits<>
#include <iostream>
int main()
{
for (;;) { // forever
int value;
while (std::cout << "Thou must enter a value divisible by 5 or 20. When finished enter -999 to leave.\n",
!(std::cin >> value) || value != -999 && value % 5 != 0 && value % 20 != 0)
// ^^ extraction failed or value does not conform to requirements
{
std::cerr << "Input error :(\nYou must enter a number divisible by 5 or 20.\n";
std::cin.clear(); // clear the flags that might have been set by a
// failed input operation.
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// ^^ discards up to the maximum value of std::streamsize characters
// until a newline character ('\n') is encountered. If we don't do that
// the next input operation will choke on the same erroneous input.
}
if (value == -999)
break;
// do sth with value
}
}
I want this to continue being done until they enter -999 but I do not know where to put my while loop or what to put if it is not entered. I also do not know where to put the "when finished enter -999 to leave" while making it eligible for all times and not just the start.
Perhaps you might want to break the problem down. Firstly, you would know that the "end condition" of this loop would be that the user keyed in -999. Hence you would want your loop to look something like
while userinput != -999
// do something here
end while loop
With that, all we need is to place the capturing of user input. One would be at the start, and one just before the while loop ends.
get userinput
while userinput != -999
// do something here
get userinput
end while loop
There are several ways to approach this problem, and that's depending on how you want to design your code. Here's my approach for this:
#include <iostream>
void Request(int& amount)
{
std::cout << "Please enter the amount of money you would like to dispense (must be in 20's or 5's)" << std::endl;
std::cout << "when finished, enter -999 to leave" << std::endl;
std::cout << ">";
std::cin >> amount;
}
int main(void)
{
int amount = 0;
for (Request(amount); amount != -999; Request(amount))
{
// Since 20 is a multiple of 5, just check if its divisble by 5 will do
if (amount % 5)
{
std::cout << "You must enter multiples of twenty or five only!" << std::endl;
continue;
}
// Otherwise print out (or do stuff here)
std::cout << amount % 5 << std::endl;
}
std::cout << "Thank you for doing business." << std::endl;
}
// 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
I am implementing a Guessing game where computer generates random number with the following code:
int main()
{
srand(time(NULL));
while (true){
int num = rand() % 10, guess, tries = 0;
while (true){
cout << "Enter number 1 to 10:";
cin >> guess;
if (tries > 2)
{
break;
}
if (guess > num)
{
cout << "Too High ! Try again"<<endl;
}
if (guess > 10)
{
cout << "Error ReEnter 1 to 10\n";
}
else if (guess < num)
{
cout << "Too Low! Try again"<<endl;
}
else
{
break;
}
tries++;
}
if (tries > 2)
{
cout <<"\nYou ran out of tries!\n";
cout << "\nThe answer is:" << num << endl;
}
else
{
cout << "\nCONGRATZ!! You guess correctly!\n";
}
return 0;
}
}
One of the problems is: yet when user attempt 3 times, the program shows "ran out of tries" even though the user input is correct on 3rd try.
Questions:
1.How do I inform user that their input exceeds 10 and show an error message to user to enter values from 1 to 10 ?
2.How to correct the aforementioned problem?
instead of writing the program for you here is some pseudo code.
get a random number rand()%10+1 1..10 call it R
loop
get user input N
if N == R then show OK and break loop
if N < R show too low
else show too high
increment tries
if tries == 3 then break loop
end loop
You have too many if else conditions that make your code unnecessarily complex, to answer your second question specifically the unwanted behaviour is caused from the:
if (tries > 2)
{
break;
}
which exits the loop regardless of the guess, as it is dependant only on the number of tries. Regarding your first question, I decided to provide you with more simple implementation that includes an answer to it as well.
You could replace your while loop with a do-while loop, terminated when the random number is guessed, i.e.:
int main(){
// initialize random seed
srand (time(NULL));
// generate a random number within [1,10]
int secretRandom = rand() % 10 + 1;
// initialize
int yourGuess = 11;
// input loop
string promptMessage = "Type a a number from 1 to 10."
do{
cout << promptMessage << '\n';
// read input
cin >> yourGuess >> endl;
// guessed number relatively to the randomly generated
if (secretRandom < yourGuess) cout << "The secret number is lower\n";
else if (secretRandom > yourGuess) cout << "The secret number is higher\n";
}while(yourGuess != secretRandom)
// if you guess the random number exit the loop and display success message
cout << "You guessed right!\n";
return 0;
}
To reduce the amount of guesses to specific number you can enclose the do-while loop and the success message in a for loop, for example:
int numberOfGuesses = 3;
for (int i = 0; i <= numberOfGuesses; ++i){
//...
}
If you want to enforce the user to input a number in the range from 1 to 10, you could do it by:
int yourGuess = 11;
int lowerBound = 0;
int upperBound = 10;
do{
cin >> yourGuess;
// not type safe
}while(yourGuess < lowerBound || yourGuess > upperBound);
On line 33, there is a break to stop the code from repeating indefinitely, but I would like it to take part in the while loop.
The Code:
#include <iostream>
using namespace std;
int main()
{
while (true){
{
cout << "This program counts by twos to any number that is inputted by the user." << endl;
cout << "Input an even number to start counting." << endl;
int input;
cin >> input;
if (!cin.fail())//fails if input is not an integer
{
if (input < 0)//makes sure all numbers are positive
{
cout << "That is not a positive number. Try again?" << endl;
}
else if (input % 2 != 0) // makes sure all numbers are even
{
cout << "That is not an even number. Try again?" << endl;
}
else{
for (int i = 0; i <= input; i += 2) //uses a for loop to actually do the counting once you know that the number is even.
{
cout << i << endl;
}
}
}
if (cin.fail())//returns this when you input anything other than an integer.
{
cout << "That is not a digit, try again." << endl;
break;
}
}
}
return 0;
}
If you guys could help me find why this repeats, that would really help.
You need to add a break statement after the for loop in order to exit the loop. Without the break the for loop will execute and print your output and then control will fall to the end of the while loop where it will start back at the top of the loop.
I would also suggest changing if (cin.fail()) to just else as you are already checking if (!cin.fail()). You also need to ignore the rest of the input and clear the error flags if you want to loop again.
You also had a extra set of brackets in the while loop. With those changes your code would be:
#include <iostream>
#include <limits>
using namespace std;
int main()
{
while (true)
{
cout << "This program counts by twos to any number that is inputted by the user." << endl;
cout << "Input an even number to start counting." << endl;
int input;
cin >> input;
if (!cin.fail())//fails if input is not an integer
{
if (input < 0)//makes sure all numbers are positive
{
cout << "That is not a positive number. Try again?" << endl;
}
else if (input % 2 != 0) // makes sure all numbers are even
{
cout << "That is not an even number. Try again?" << endl;
}
else{
for (int i = 0; i <= input; i += 2) //uses a for loop to actually do the counting once you know that the number is even.
{
cout << i << endl;
}
break; // exit the while loop
}
}
else //else when you input anything other than an integer.
{
cout << "That is not a digit, try again." << endl;
cin.clear(); // reset the error flags
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // clear any extra input
}
}
return 0;
}
Based on the error message you print, I'm guessing your problem is that you want to give the user a chance to try again to enter a number, but after one failure, it continuously fails no matter what you enter. If that's the case, replace your break with cin.clear(). That will tell the stream that you've recovered from the error and are ready to receive more input.
If you're going to do that, though, your program now has no exit condition, so you'll want to add a break (or return 0) just after the for-loop.
I have these block of codes that belong to a NIM subtraction game. The thing that I would like to implement is that user is going to be able play the game as long as he/she wants. Simply if user enters 999 program will exit, otherwise user will be playing until he/she enters 999. Here is my block of codes. I am not sure that I make a logical mistake or I need to add some specific exit code. Thanks for your time and attention.
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int total, n;
while(true){
cout << "Welcome to NIM. \nEnter 999 to quit the game!\nPick a starting total: ";
cin >> total;
if(total==999)
break;
while(true){
//pick best response and print results.
if ((total % 3) == 2)
{
total = total - 2;
cout << "I am subtracting 2." << endl;
}
else
{
total--;
cout << "I am subtracting 1." << endl;
}
cout << "New total is " << total << endl;
if (total == 0)
{
cout << "I win!" << endl;
break;
}
// Get user’s response; must be 1 or 2.
cout << "Enter num to subtract (1 or 2): ";
cin >> n;
while (n < 1 || n > 2)
{
cout << "Input must be 1 or 2." << endl;
cout << "Re-enter: ";
cin >> n;
}
total = total - n;
cout << "New total is " << total << endl;
if (total == 0)
{
cout << "You win!" << endl;
break;
}
}
}
return 0;
}
You are modifying total inside the loop. Just test after cin>>total at the beginning if total==999 and break if true, i.e.
if(total==999)
break;
and replace the do-while loop by a while(true){}
In the do-while loop you are trying to compare character literal '999' with variable total that has type int.
}while(total!='999');
Though this code is valid its result can be something else than you are expecting. Values of character literals with more than one symbol are implementation defined.
You have to write
} while ( total != 999 );
Also if the player will enter 999 you start to play with him though you have to exit the game.
So in my opinion it is better to use while loop. For example
while ( true )
{
cout << "Welcome to NIM. \nEnter 999 to quit the game!\nPick a starting total: ";
cin >> total;
if ( total == 999 ) break;
// ...
}
you have to do three corrections in your code to make it right
first you have to check if total is equal to 999, then break in your do loop just after getting the total from user
second - you have to put same condition in your first while loop
and lastly - instead of while(total!='999') u shall write while(total!=999) because it is integer