When I enter a value between 0 to 70 it prints infinitely (which is wrong), but when input a number that is not between 0 to 70 it prompts the user to enter a number that should be between 0 to 70. (which is correct)
while (true)
{
if (hourswork < 0 || hourswork > 70)
{
cout<<"Please enter a value between 0 to 70: ";
cin>>hourswork;
}
else
{
wages = RATE * hourswork;
cout << "The wage is: " << wages << endl;
}
}
The result when I enter a value between 0 to 70 should only be printed once.
You should reconsider what you have in your while loop. Do you really want the output in there? You probably only want the loop to get input until it's valid. The output should instead be moved out of the loop:
int main() {
int hourswork = -1;
int RATE = 123;
while (hourswork < 0 || hourswork > 70)
{
cout << "Please enter a value between 0 to 70: ";
cin >> hourswork;
}
int wages = RATE * hourswork;
cout << "The wage is: " << wages << endl;
}
This way it will ask for a hourswork value until it is valid, which then stops the loop, and unconditionally does the print part once after the loop.
Generally the reason why your loop never terminated is because while (true) won't stop looping unless you get out of it with a break, return or something similar, neither of which is present in your code.
You need to leave your loop with a break when your hourswork was within range.
Like this:
while (true)
{
if (hourswork < 0 || hourswork > 70)
{
cout<<"Please enter a value between 0 to 70: ";
cin>>hourswork;
}
else
{
wages = RATE * hourswork;
cout << "The wage is: " << wages << endl;
break;
}
}
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;
}
Here is the objective: "Write a c++ program which prompts the user to enter some numbers and finds the minimum, maximum, and count
(number) of the entered numbers separately for the positive and negative numbers. It then prints out this information
in the correct format. Entering 0 should terminate the input sequence and cause the results to be displayed.
My problem is, when I run the code through www.cpp.sh, it seems to be storing the 0 that I use to end the sequence to a maximum or a minimum variable (posmax and negmax or posmin and negmin). My while loop's condition is number_entered !=0, so 0 shouldn't even be going into the loop...
if the first 3 in the sequence are negative and the last 3 are positive; if the first 3 in the sequence are positive and the last 3 are negative
Stranger still, the 0 being stored as a minimum or negative only seems to happen to the last sequence of variables entered.
Relevant code:
int main()
{
double number_entered, posmax, posmin, negmax, negmin;
int positive_count, negative_count;
positive_count = 0;
negative_count = 0;
posmax = 0;
posmin = 0;
negmax = 0;
negmin = 0;
//before it goes into a loop it will do the following:
cout << "Entering 0 will terminate the sequence of values.\n" << endl;
cout << "Enter a number: ";
cin >> number_entered; //stores input to number_entered
if (number_entered > 0) //if positive
{
posmax = number_entered; //needs to be initialized before use in loop
posmin = number_entered; //needs to be initialized before use in loop
}
else if (number_entered < 0) //if negative
{
negmax = number_entered; //needs to be initialized before use in loop
negmin = number_entered; //needs to be intiialized before use in loop
}
while (number_entered !=0) //will keep looping as long as the while condition is true
{
if (number_entered > 0) //branch if number_entered is positive
{
if ( number_entered > posmax) //sub-branch to compare to get max
{
posmax = number_entered; //if number is larger than the current max, it gets stored as the new max
}
else if ((number_entered < posmin)||(posmin == 0)) //sub-branch to compare to get min; since posmin is initialized to 0 it needs to be updated
{
posmin = number_entered; //if number is less than min than it gets stored as the new min
}
positive_count++; //under main if branch for if the number is positive, add to positive_count
}
else if (number_entered < 0) //branch for if number_entered is negative
{
if ( number_entered > negmax) //sub-branch if number_entered is more than the max
{
negmax = number_entered; //it then gets stored as the new negmax
}
else if ((number_entered < negmin)||(negmin == 0)) //sub-branch if number_entered is less than min; since negmin is initialized to 0 it needs to be updated
{
negmin = number_entered; //it then gets stored as the new negmin
}
negative_count++;
}
cout << "Enter a number: "; //prompts for input again after it is done counting, and comparing to store a max and min
cin >> number_entered;
} //end of while loop
if (number_entered == 0)
{
cout << endl;
if ((negative_count > 0) && (positive_count > 0)) //for situations where it received both positive and negative values
{
cout << "There were " << negative_count << " negative values entered, with minimum "<< negmin << " and maximum " << negmax << endl << endl;
cout << "There were " << positive_count << " positive values entered, with minimum "<< posmin << " and maximum " << posmax << endl<< endl;
}
else if (negative_count > 0 && positive_count == 0) //for sitautions where only negative input was received
{
cout << "There were " << negative_count << " negative values entered, with minimum "<< negmin << " and maximum " << negmax << endl << endl;
cout << "No positive numbers were entered" << endl;
}
else if (positive_count > 0 && negative_count == 0) //for situations where only positive input was received
{
cout << "There were " << positive_count << " positive values entered, with minimum "<< posmin << " and maximum " << posmax << endl<< endl;
cout << "No negative numbers were entered" << endl;
}
else if (negative_count == 0 && positive_count == 0) //for if only 0 was received
{
cout << "No positive numbers were entered.\n"
<< endl
<< "No negative numbers were entered.\n"
<< endl;
} //end of nested branching if-else if statement
} //end of if statement
return 0;
}
I figured it out finally, but maybe I posted the answer badly and that was why I didn't get the answer I needed.
in order to get a max that wasn't 0 for the negative values, I simply needed to move my || (negmax == 0) condition to the correct if statement (it was on the minimum branch).
There were no other issues with the program.
Because your initial values are zeros. There is no way that you will enter number lower (for positives) and higher (for negatives) than zero.
I'm having a problem with the input validation of my do-while loop. My do-while loop only validates every other input
Here's an example:
Please Enter Grade 1: 101 (It does not accept input)
Invalid Rage. Please Enter Range 0-100.
Please Enter Grade 1: 101 (It accapts this input)
Please Enter Grade 2: 101 (It does not accept input)
Invalid Rage. Please Enter Range 0-100.
Please Enter Grade 2: 101 (It accapts this input)
Here's My Code:
for(vector<double>::size_type i = 0; i < 15; i++)
{
do
{
cout << "Please Enter Grade "<< i + 1 <<": " << flush;
cin >> gradesVector[i];
}
while(gradesVector[i] < 0.0 && gradesVector[i] > 100.0);
{
cout << "Invalid Rage. Please Enter Range 0-100:\n";
cout << "Please Enter Grade "<< i + 1 <<": " << flush;
cin >> gradesVector[i];
}
}
Try this:
int main() {
vector<double> gradesVector(15);
for(vector<double>::size_type i = 0; i < 15; i++) {
do {
cout << "Please Enter Grade "<< i + 1 <<": " << flush;
cin >> gradesVector[i];
} while(gradesVector[i] < 0.0 || gradesVector[i] > 100.0);
}
}
The statement while(gradesVector > 0.0 && gradesVector <= 100.0) is trying to check if the entire vector is greater than 0 or less than 100, which doesn't really make sense. You want to do something like while(gradesVector[i] > 0.0 && gradesVector[i] <= 100.0) (just make sure i is in the correct scope).
Edit: just get rid of the do-while loop and only use a for-loop. Inside the for-loop, add an if-statement: if(gradesVector[i] > 0.0 && gradesVector[i] <= 100.0). If the validation fails, use a break statement to exit the for-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
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