How do I exit out of my do while loop? c++ [duplicate] - c++

This question already has answers here:
Immediate exit of 'while' loop in C++ [closed]
(10 answers)
Closed 3 years ago.
Ok before anyone bashes me, I checked every forum to try to help me solve this problem but unfortunately cannot solve it. Can someone point to the right direction to solve this? I am trying to exit this do while loop immediately when inputting the value -1. For example I want the output to look like this when I input -1:
Enter the expected number of hours charging:
//user enters -1
Exiting...
#include <iostream>
#include<iomanip>
using namespace std;
int main() {
float hour;
float Network1, Network2, Network3;
do {
cout << "Enter the expected number of hours charging:" << endl;
cin >> hour;
Network1= (1 * hour) + 10;
Network2= (2.50 * hour);
Network3 = (0.50 * hour) + 20;
cout << "Your expected costs are: " << endl;
cout << "Network 1: $" << fixed << setprecision(2) << Network1 << endl;
cout << "Network 2: $" << fixed << setprecision(2) << Network2 << endl;
cout << "Network 3: $" << fixed << setprecision(2) << Network3 << endl;
if(Network1 < Network2 && Network1 < Network3){
cout << "The lowest cost network is $" << Network1 << endl;
}
else if (Network2 < Network1 && Network2 < Network3){
cout << "The lowest cost network is $" << Network2 << endl;
}
else{
cout << "The lowest cost network is $" << Network3 << endl;
}
}
while (hour != -1) ;
cout << "Exiting..." << endl;
return 0;
}

There is two ways:
You can check input right after read
cin >> hour;
if (hour == -1) {
break;
}
You can use while loop and read value twice. First one before the first iteration and the second in the end
cout << "Enter the expected number of hours charging:" << endl;
cin >> hour;
while (hour != -1) {
// ...
cout << "Enter one more value:" << endl;
cin >> hour;
}

There are two basic ways of doing this, the neanderthal way and the cromagnon way.
The neanderthal way;
for(;;) {
cout << "Enter the expected number of hours charging:" << endl;
cin >> hour;
if (!cin || hour == -1) break;
...
The cromagnon way:
while (std::cout << "Enter the expected number of hours charging: \n" &&
std::cin >> hour &&
hour! = -1) {
...
Methods that do not involve checking of cin properly belong to pithecanthrops.

Related

I am having problems with rejecting negatives within my function

I was doing a school assignment involving functions, it wasn't too hard until I learned I needed to reject negative numbers as variables. It doesn't reject the numbers and instead just skips the next variable and then will loop to a seemingly random variable random variables in the code when the function completes.
void InPatient()
{
int DaysIn = 0;
double DailyRate{};
double MedicationCharges{};
double ServiceCharges{};
cout << "Please enter number of days patient stayed (Rounded up):" << endl;
cin >> DaysIn;
//I tried to use while statements to solve this problem and it hasn't worked
while (DaysIn != 50000000000)
{
if (DaysIn >= 0)
{
cout << "Please enter hospital's daily rate as a decimal (Ex: .35, .265):" << endl;
cin >> DailyRate;
}
else if (DaysIn < 0)
{
cout << "That is not a valid number in the system" << endl;
}
if (DailyRate >= 0)
{
cout << "Please enter medicine charges:" << endl;
cin >> MedicationCharges;
}
else if (DailyRate < 0)
{
cout << "That is not a valid number in the system" << endl;
}
//I tried these else if statements to reject negative numbers and loop back but it just says "It doesn't work" and continues on.
if (MedicationCharges >= 0)
{
cout << "Please enter service charges (for lab testing or whatnot):" << endl;
cin >> ServiceCharges;
}
else if (MedicationCharges < 0)
{
cout << "That is not a valid number in the system" << endl;
}
if (ServiceCharges >= 0)
{
double DaysInFee = DaysIn / DailyRate;
double HospitalBill = DaysInFee + MedicationCharges + ServiceCharges;
cout << "Patient's Stay Fee: $" << DaysInFee << "\n";
cout << "Medication Charges: $" << MedicationCharges << "\n";
cout << "Service Charges: $" << ServiceCharges << "\n";
cout << "Patient's total is $" << std::setprecision(2) << std::fixed << HospitalBill << " " << "today." << endl;
}
else if (ServiceCharges < 0)
{
cout << "That is not a valid number in the system" << endl;
}
}
}
void OutPatient()
{
double MedicationCharges = 0;
double ServiceCharges{};`
//I've done something different down here, but it does the exact same thing
while (MedicationCharges != 50000000000)
{
cout << "Please enter medicine charges:" << endl;
cin >> MedicationCharges;
cout << "Please enter service charges (for lab testing or whatnot):" << endl;
cin >> ServiceCharges;
double HospitalBill = MedicationCharges + ServiceCharges;
cout << "Medication Charges: $" << MedicationCharges << "\n";
cout << "Service Charges: $" << ServiceCharges << "\n";
cout << "Patient's total is $" << std::setprecision(2) << std::fixed << HospitalBill << " " << "today." << endl;
if (MedicationCharges < 0)
{
cout << "That is not a valid number in the system" << endl;
}
//These just say "These don't work" but let's the code use them anyways.
else if (ServiceCharges < 0)
{
cout << "That is not a valid number in the system" << endl;
}
}
}
As stated in the code, I have used while and if statements to reject negatives, but it doesn't reject them.
Add a continue in your else if blocks to restart the while-loop after an incorrect input
Alternatively, add a break or return statement to leave the loop or function. It depends what you want to do in the error case.

how to accept only whole numbers in c++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am new to programming and I need help with my term project. I have made a program that simulates a hotel booking, the problem is that whenever a non-whole number is entered for the first question, it goes into an infinite loop. If you get to the second question and enter a non-whole number it accepts it as a whole number by dropping off anything that comes after the decimal and then skips the next question and stops running the program.
#include <iostream>
#include <string>
using namespace std;
int stay_length (int stay)
{
int nights = stay;
int total = 0*nights;
return total;
}
int rooms_booking(int rooms)
{
int rooms_booked = rooms;
int total = 0;
if(rooms_booked > 0)
{
total = rooms_booked * 50;
}
else
{
total = 0;
}
return total;
}
int main(){
int x;
string repeat;
int nights;
int total = 0;
int rooms_avail = 10;
int rooms;
cout << "Hello! Welcome to Hotel COMP 150." << endl;
do {
if (rooms_avail > 0) {
cout << "How many nights will you be staying?" << endl;
}
else {
cout << "Sorry, but there are no rooms available. " << endl;
}
do {
cin >> nights;
if (nights > 0 && nights <= 28)
{
int total1 = stay_length(nights);
cout << "You are staying for " << nights << " nights" << endl;
cout << "That costs: $" << total1 << endl;
total = total + total1;
}
else
{
cout << "You cannot stay less than 1 or more than 28 nights" << endl;
}
} while (nights <= 0 || nights >28);
if (rooms_avail > 0)
{
cout << "How many rooms will you be booking?" << endl;
cout << "There are " << rooms_avail << " available." << endl;
cin >> rooms;
if (rooms > 0 && rooms <= rooms_avail)
{
int total2 = rooms_booking(rooms);
cout << "You are booking " << rooms << " rooms." << endl;
cout << "That costs : $" << total2 << endl;
total = total + total2;
rooms_avail = rooms_avail - rooms;
}
else if (rooms <= 0 || rooms > rooms_avail)
{
do{
cout << "You can only book a minimum of 1 room or a maximum of " << rooms_avail << endl;
cin >> rooms;
} while (rooms <= 0 || rooms > rooms_avail );
int total2 = rooms_booking(rooms);
cout << "You are booking " << rooms << " rooms." << endl;
cout << "That costs : $" << total2 << endl;
total = total + total2;
rooms_avail = rooms_avail - rooms;
}
else
{
cout << "You cannot book more than " << rooms_avail << endl;
}
}
else
{
cout << "Sorry, all rooms have been booked." << endl;
}
cout << "Your total so far is: $" << total << endl;
cout << "Would you like to make another booking? Enter 'Y' or 'y' to do so." << endl;
cin >> repeat;
}while(repeat == "Y" || repeat == "y");
return 0;
}
It's always better to use std::getline() instead of operator>> to read interactive input from std::cin.
operator>> is not for reading a single line of text from standard input, and storing it. That's what std::getline() is for.
If the wrong kind of input is entered, not what operator>> expects, it sets std::cin to a failed state, which makes all future attempts to read std::cin immediately fail, resulting in the infinite loop you are observing.
To do this correctly, it is going to be either:
1) Always check fail() after every operator>>, to see if the input failed, if so recover from the error with clear(), then ignore(). This gets real old, very quickly.
2) It's much easier to read a single line of text with std::getline(), then parse the input yourself. Construct a std::istringstream, if you wish, and use operator>> with that, if that makes it easier for you.
You can achieve basic user-input error checking via the console with something along these lines:
int nights = 0;
// error checking loop
while(1) {
std::cout << "How many nights will you be staying?" << endl;
std::cin >> nights;
// input valid
if(!std::cin.fail() && (std::cin.peek() == EOF || std::cin.peek() == '\n')
&& nights > 0 && nights <= 28) {
// do stuff
break; // break from while loop
}
// input invalid
else {
std::cin.clear();
std::cin.ignore(256, '\n');
std::cout << "An input error occurred." << std::endl;
}
}

Why does one of my 'while' statements execute when another one of my 'while' statements is true?

Note: I am using C++
Why does one of my 'while' statements ('while' number 1) execute anyway when another one of my 'while' statements ('while' number 2) placed above it is valid? This bothers me, because though 'while' number 1 is not true, but 'while' number 2 is true, 'while' number 1 executes anyway instead of 'while' number 2. Can anyone help me, or explain this? Here is my code:
#include <iostream>
#include <string>
using namespace std;
void PancakeGlutton()
{
int answer;
cout << "Good morning!" << endl;
cout << "Would you like to enter pancake data? Press 1 to accept, press 2 to decline: ";
cin >> answer;
while (answer == 1) {
int totalPeople = 10;
int totalPancakes = 0;
int input;
int lowest = 100000;
int highest = 0;
for (int i = 9; i >= 0; --i) {
cout << "How many pancakes did you eat this morning? I will be asking this question " << i << " more times." << endl;
cin >> input;
totalPancakes += input;
if (input >= highest) {
highest = input;
}
if (input <= lowest) {
lowest = input;
}
}
double pancakeAverage = double(totalPancakes) / double(totalPeople);
cout << "The total number of pancakes eaten was " << totalPancakes << " pancakes " << endl;
cout << "The average number of pancakes eaten was " << pancakeAverage << " pancakes " << endl;
cout << "The highest number of pancakes eaten was " << highest << " pancakes" << endl;
cout << "The lowest number of pancakes eaten was " << lowest << " pancakes" << endl;
cout << "" << endl;
cout << "Do you want to enter more pancake data? Press 1 to accept, press 2 to decline: ";
cin >> answer;
}
// while number 1:
while (answer == 2) {
break;
}
// while number 2:
while (answer != 1 || answer != 2) {
cout << "Error: please enter a valid answer. 1 or 2? ";
cin >> answer;
}
}
int main()
{
PancakeGlutton();
system("PAUSE");
return EXIT_SUCCESS;
}
while (answer != 1 || answer != 2) {
cout << "Error: please enter a valid answer. 1 or 2? ";
cin >> answer;
}
must be
while (answer != 1 && answer != 2) {
cout << "Error: please enter a valid answer. 1 or 2? ";
cin >> answer;
}

Looping failure

I need to make the program loop until the user inputs "XXXX" as the name. Problem is, my code only loops once at most and exits. I have tried messing with do ... whiles for an entire day and can't seem to figure this out but I feel like i'm really close!
Edit:
You guys are awesome! Made both of the changes but now it skips the name prompt and goes straight to the deposit prompt. How would i get it to include the name prompt in the loop?
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main() {
string name, XXXX;
float deposit, time, interest, total, totinterest;
int compound;
cout << left;
int flag = 0;
do {
cout << "Enter your name or XXXX to stop: ";
getline(cin, name);
cout << name << " enter the following information: " << endl;
if (name == "XXXX"){
flag = 1;
}else
{
cout << setw(60) << "\tAmount on deposit: ";
cin >> deposit;
if (!deposit || deposit < 0){
cout << "\tPlease enter a positive number! ";
}
cout << setw(60) << "\tYears on deposit: ";
cin >> time;
if (!time || time < 0){
cout << "\tPlease enter a positive number! ";
return(0);
}
cout << setw(60) << "\tNumber of times the interest is compounded per year: ";
cin >> compound;
if (!compound || compound < 0){
cout << "\tPlease enter a positive number! ";
return(0);
}
if (time >= 5)
interest = .045;
else if (time >= 4)
interest = .04;
else if (time >= 3)
interest = .035;
else if (time >= 2)
interest = .025;
else if (time >= 1)
interest = .02;
else if (time < 1)
interest = .015;
total = (deposit)*pow((1 + interest / compound), (compound * time));
totinterest = total - deposit;
cout << left << setprecision(2) << fixed;
cout << endl;
cout << setw(15) << "Name " << setw(14) << "Years" << setw(18) << "Deposit Amount" << setw(18) << "Interest Earned " << setw(18) << "Total" << endl;
cout << "===============================================================================" << endl;
cout << setw(15) << name << setw(14) << time << setw(1) << "$" << setw(17) << deposit << setw(1) << "$" << setw(17) << totinterest << setw(1) << "$" << setw(18) << total << endl;
cout << endl;
cout << "Thank you for using tax program. Have a nice day. " << endl;
return(0);
}
} while (flag = 0);
}
return(0) will get you out of the main. Remove that line and retry.
return(0) will exit the main() and the program will terminate. Hence, remove it from the source.
Also the condition in while (flag = 0) will always return false. Change it to while (flag == 0) otherwise it would result in a loop that iterates only once.
And finally, you need <math.h> for the pow() function.
#include <math.h>
Because you are using = instead of == in while condition.
Change flag = 0 to !flag or flag==0.
Apart from this, you have return 0 which is unconditional. This return statement will make the program to exit anyhow.
You have to include
#include <math.h>
for your pow function to work. I get an error that pow is not defined.
Firstly, you want your while condition to be
while(flag == 0) and not while (flag = 0)
Also, if the user enters an invalid value of time or deposit or compound(such as less than 0), then your code prints out an error message and quits. Instead, you want to put a while loop there that keeps prompting the user for a valid input as long they keep giving an incorrect input.
Finally, you wanna be using something like myString.compare(otherString) instead of the == operator
You have a return(0); in your else clause. Also, you have = instead of == in your while loop, which (after you remove the return statement) is a recipe for an infinite loop.

How can I get user input to exit a loop?

I have a problem with my code, every time I loop it with the answer 'y'(Yes) it loops to infinity?
I'm trying to make a loan calculator and every time the user is done calculating with a transaction and wants to reset, and do another calculation if he enters in a value 'y', and if he enters 'n' the program will end.
Here's my code so far:
#include <iostream>
#include <string>
#include <iomanip>
#include <cmath>
using namespace std;
int main() {
char ans = 'y';
do {
string name;
int Months;
int n;
double LoanAmount, Rate, MonthlyInterest, TotalLoanAmount, MonthlyAmortization, OutstandingBalance;
cout << fixed << showpoint;
cout << "Enter Name of Borrower: ";
getline(cin, name);
cout << "Enter Loan Amount: ";
cin >> LoanAmount;
cout << "Enter Number of Months to Pay: ";
cin >> Months;
cout << "Enter Interest Rate in Percent(%): ";
cin >> Rate;
cout << setprecision(2);
MonthlyInterest = LoanAmount * Rate;
TotalLoanAmount = LoanAmount + (MonthlyInterest * Months);
cout << "Monthly Interest: " << MonthlyInterest << endl
<< "Total Loan Amount with interest: " << TotalLoanAmount << endl;
cout << setw(100)
<< "\n\tSUMMARY OF OUTSTANDING INSTALLMENT" << endl
<< "\tName of Borrower: " << name
<< "\n\nMonth\t\tMonthly Amortization\t\tOutstanding Balance"
<< "\n";
for(n = 1; n <= Months; n++) {
MonthlyAmortization = TotalLoanAmount / Months;
OutstandingBalance = TotalLoanAmount - MonthlyAmortization;
cout << n << "\t\t" << MonthlyAmortization << "\t\t\t" << n - 1 << OutstandingBalance << endl;
}
cout << "\nEnd of Transaction";
cout << "Do you want to compute another transaction?[y/n]?" << endl;
cin >> ans;
}
while(ans == 'y');
}
After your cin>>ans, add these two lines :
cin.clear();
cin.sync();
That usually fixes a lot of the infinite looping problems I get with cin.
Also, I would recommend against initializing ans as 'y' when you declare it. I don't think this is causing you problems but it's an uncessesary thing.
You seem to expect pressing y and enter to register as only 'y'. If you want to get the input of just one character have a look at std::cin.get(char)