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
Related
I am trying to get this 'do while' loop to run 3 times and then display the amount in the accumulator contain within a while loop inside the 'do while' loop.
It seems to be counting correctly, but only runs the while loop on the first. When run, instead of going on to ask for the next set of numbers, it just displays the first batch (added up correctly). I have tried switching some of the code around and searching google, but can't find the answer.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int storeNum = 1;
int payRollAmount = 0;
int totalPayroll = 0;
do
{
cout << "Store " << storeNum << ":" << endl;
while (payRollAmount <= -1)
{
cout << "Enter Store's Payroll Amount (-1 to exit): ";
cin >> payRollAmount;
totalPayroll += payRollAmount;
}
storeNum++;
} while (storeNum <= 3);
cout << "The Total Payroll is: " << totalPayroll << endl;
system("pause");
return 0;
}
The code should take in an unknown amount of "payrolls," allow you to exit using -1, and then continue on to the next stores payrolls. It should do this 3 times, and then display the total amount (all numbers entered added together.
Hi perhaps reset payRollAmount at each iteration? That way it will continue to request the input.
for (int amount = 0; amount != -1; ) {
cout << "Enter Store's Payroll Amount (-1 to exit): ";
cin >> amount;
totalPayroll += amount;
}
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
This program will play a game with the user, called Odds and Evens. The computer will play Evens, and the human user will play Odds. For a round of the game, each player picks an integer in the range [1,10]. The players pick their numbers independently: neither player knows the other player's number before choosing its own number. If the sum of the numbers is even, then Evens (the computer) wins that round; if the sum of the numbers is odd, then Odds (the human) wins that round. The game continues for as many rounds as the user want to play; the user ends the game by typing a non-# or a number outside [1,10] for the input. At the end of the game, the program summarizes the score.
I am having trouble properly looping this question. Randomizing the number pc chooses is not working as every round in the game the pc chooses the same number. Also i do not know how I would have the program summarize the score. Help would be much appreciated as I have another problem for homework that is similar to this!
Here is my code:
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <string>
#include <iomanip>
#include <ctime>
using namespace std;
bool die(const string & msg);
int main(){
srand(static_cast<unsigned>(time(0)));
unsigned num1 = 0, num = 0, sum = 0;
bool userTurn = true;
cout << "Welcome to the Odds and Evens game!";
num = rand() % 10 + 1;
while (num){
if (userTurn){
cout << " Your # in [1,10] is ";
cin >> num1;
}
else {
cout << "My number is " << num;
sum = num1 + num;
if (sum % 2 == 0){
cout << " I win!";
}
else {
cout << " You win!";
}
}
userTurn = !userTurn;
}
}
bool die(const string & msg){
cout << "Fatal error: " << msg << endl;
exit(EXIT_FAILURE);
}
Randomizing the number pc chooses is not working as every round in the game the pc chooses the same number.
You don't have code to re-set the value of num when it's the computer's turn.
After the line
userTurn = !userTurn;
add
if ( !userTurn )
{
num = rand() % 10 + 1;
}
Also i do not know how I would have the program summarize the score.
Keep two counters that indicate how many times the human won and how many times the computer won.
int computerWinCount = 0;
int humanWinCount = 0;
and then, update the loop to use:
if (sum % 2 == 0){
cout << " I win!";
++computerWinCount;
}
else {
cout << " You win!";
++humanWinCount;
}
The conditional of the while loop is such that your program will never terminate. Update it to something like below.
while (true) {
if (userTurn){
cout << " Your # in [1,10] is ";
cin >> num1;
// If the user entered a number that is not
// within range or the user did not input a number,
// then break out of the loop.
if ( !cin || num1 < 1 || num1 > 10 )
{
break;
}
}
else {
cout << "My number is " << num;
sum = num1 + num;
if (sum % 2 == 0){
cout << " I win!" << endl;
++computerWinCount;
}
else {
cout << " You win!" << endl;
++humanWinCount;
}
}
userTurn = !userTurn;
if ( !userTurn )
{
num = rand() % 10 + 1;
}
}
To report the summary, add the following lines before the end of the main.
cout << "Number of times I won: " << computerWinCount << endl;
cout << "Number of times you won: " << humanWinCount << endl;
Here:
num = rand() % 10 + 1;
while (num){
... // never change num
}
Do you see the problem? The computer player chooses num randomly, but only once. Just put another num = rand() % 10 + 1; inside the main loop.
(Also, you don't seem to have a way for the user to terminate the game.)
So you want a simple loop that will do the following things.
get the user input.
get the computer input
check to see who win's the current round
update scores.
this happens until the user chooses an option not from 1 to 10
after this you want to display the score.
Here is a complete example.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main(){
int mynum, compNum, myScore(0), compScore(0);
srand(time(NULL));
cout << "Welcome to the Odds and Evens game!" << endl;
cout << "Your # in [1,10] is ";
while ((cin >> mynum) && mynum > 0 && mynum <= 10){
compNum = rand()%10 + 1;
if ((mynum + compNum)%2){
cout << "You win" << endl;
++myScore;
} else {
cout << "Computer Wins" << endl;
++compScore;
}
cout << "Your # in [1,10] is ";
}
cout << "You won " << myScore << " games" << endl;
cout << "The computer won " << compScore << " games" << endl;
return 0;
}
Your problem with the computer's number not changing is due to the fact you do not update its value within the loop.
If you want to keep track of the score, you can simply keep two integers that keep track of how many times the user has won and how many times the computer has won. Then at the end (after the while loop) cout each of their scores.
Overall your code is pretty close.
You just need to make sure you update the computer's guess inside the while loop and when you decide who's won the round increment that person's score.
The whole loop condition in your original code will always evaluate to true. As num will always be to a number 1 to 10. You'll want to use the user's input in the while loop condition.
The while condition in my code will do the following:
get the user's input. cin >> mynum will evaluate to false if cin fails to read a number. If it did read a number the condition will check to see if the number is between 1 and 10 inclusive.
For this loop, I need to be able to enter names into an array that has to be 100 elements long, and exit the array to read the names back once Q or q is entered, or the end of the array is reached. When I use this code, the program goes back to the beginning of the while loop without breaking the for loop.
for (int i = 0; i < 100; i++)
{
while (true)
{
cout << "Enter Player Name (Q to quit): ";
getline(cin,playerName[i]);
if (playerName[i] == "Q" || playerName[i] == "q")
break;
cout << "Enter score for " << playerName[i] << ": "<< endl << endl;
}
}
According to your description, it seems like the while (true) is completely redundant!!!
So you should simply do:
int i;
for (i = 0; i < 100; i++)
{
cout << "Enter Player Name (Q to quit): ";
getline(cin,playerName[i]);
if (playerName[i] == "Q" || playerName[i] == "q")
break;
cout << "Enter score for " << playerName[i] << ": "<< endl << endl;
}
At this point, you can use i in order to tell how many names have been entered by the user.
This is one of the rare circumstances where a judicious goto may be the best available option.
for (...)
{
while (...)
{
if (...)
goto exit_loop;
}
}
exit_loop:;
Some languages let you put a label on the for and use it in break, but C and C++ are not among them. It can also make sense to extract the entire loop nest to its own function, allowing you to use return to exit both loops, but this may not work in context.
I personally think that this use of goto is easier to understand than a boolean + if in the outer loop, as suggested in other answers, but reasonable people can disagree about that.
If I'm reading your question correctly, then you don't need the while loop. Without that while loop, break will exit the for loop, then you can enter a separate for loop (from 1 to 100) to print the contents of the array.
If the user enters less than 100 names at any point, then the second for loop will go from 1 to i, and output each array entry along the way.
I'm answering the title - wrap both loops in a function:
void foo()
{
for (;;)
while (true)
if (/* something */)
return;
}
I otherwise agree with barak manos, you don't even need two loops.
Add a boolean variable to tell you if the inner loop has broken:
bool broken = false;
for (int i = 0; i < 100; i++)
{
while (true)
{
cout << "Enter Player Name (Q to quit): ";
getline(cin,playerName[i]);
if (playerName[i] == "Q" || playerName[i] == "q") {
broken = true;
break;
}
}
cout << "Enter score for " << playerName[i] << ": "<< endl << endl;
}
if (broken) {
break;
}
}
use a boolean variable to state that you breaked from the inner loop and then check it and break from the outer loop if needed.
Try the following
bool done = false;
int i = 0;
for ( ; i < 100 && !done; i++ )
{
cout << "Enter Player Name (Q to quit): ";
getline(cin,playerName[i]);
if ( !( done = playerName[i] == "Q" || playerName[i] == "q" ) )
{
cout << "Enter score for " << playerName[i] << ": "<< endl << endl;
// some code for entering the score
}
}
Take into account that you need to keep variable i that to know how many players were entered. So I defined i outside the loop.