I am having problems with rejecting negatives within my function - c++

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.

Related

How do I go about fixing my calculator answers in my c++ program with a basic menu?

I have a basic menu program that gives the user different programs to choose from and run, when I run the simpleCalculator option and iput values and the operation of arithmetic the output is always the wrong answer but when I first programmed the calculator program without the menu and it being in its own function it would run just fine and give the the right answers, what exactly is going wrong here?
Ignore the third option in the menu since i haven't added code for the prime number checker program
double first_arg;
double second_arg;
string arithmeticOperation;
int numBottles = 99;
double simpleCalculator()
{
cout << "Enter first value: ";
cin >> first_arg;
cout << "Enter choice of arithmetic operation:\n* = multiplication\n/ = division\n+ = addition\n- = subtraction\n\n";
cin >> arithmeticOperation;
cout << "\nEnter second value: ";
cin >> second_arg;
if(arithmeticOperation == "*")
{
cout << "\nYour answer is " << first_arg * second_arg;
}
else if(arithmeticOperation == "/")
{
cout << "\nYour answer is " << first_arg / second_arg;
}
else if(arithmeticOperation == "+")
{
cout << "\nYour answer is " << first_arg + second_arg;
}
else if(arithmeticOperation == "-")
{
cout << "\nYour answer is " << first_arg - second_arg;
}
else
{
cout << "\nPlease enter a valid choice of an arithmetic operation\n";
}
}
string bottlesProgram()
{
while(true)
{
if (numBottles > 2)
{
cout << numBottles << " bottles of beer on the wall\n" << numBottles << " bottles of beer!\n" << "Take one down\nPass it around\n" << numBottles - 1 << " bottles of beer on the wall.";
cout << "\n\n";
}
else if(numBottles == 2)
{
cout << numBottles << " bottles of beer on the wall\n" << numBottles << " bottles of beer!\n" << "Take one down\nPass it around\n" << numBottles - 1 << " bottle of beer on the wall.";
cout << "\n\n";
}
else if(numBottles == 1)
{
cout << numBottles << " bottle of beer on the wall\n" << numBottles << " bottle of beer!\n" << "Take one down\nPass it around\n" << numBottles - 1 << " bottles of beer on the wall.";
cout << "\n\n";
}
else if(numBottles == 0)
{
cout << "No more bottles of beer on the wall,\nNo more bottles of beer.\nGo to the store and buy some more,\n" << "99 bottles of beer on the wall...";
cout << "\n\n";
}
else
{
break;
}
numBottles--;
}
}
int main()
{
int menuInput;
cout << " ***Programs Menu***\n" << "------------------------------------------\n" << "1. Run a simple Calculator\n" << "2. Run 99 bottles of beer on the wall song\n" << "3. Run prime number checker program\n" << "------------------------------------------\n";
cin >> menuInput;
if(menuInput == 1)
{
cout << simpleCalculator();
}
else if (menuInput == 2)
{
cout << bottlesProgram();
}
}
You seem to be confused about returning values from a function, and printing values in a function. These are not the same thing.
If you print the values in the function then the function should be void (i.e. nothing is returned) and the printing happens inside the function (obviously)
void simpleCalculator()
{
...
cout << "\nYour answer is " << first_arg * second_arg;
...
}
simpleCalculator(); // no cout
On the other hand if you return a value from the function then the function is not void and the printing happens outside the function
double simpleCalculator()
{
...
return first_arg * second_arg; // return not cout
...
}
cout << "\nYour answer is " << simpleCalculator();
Your code is doing half one version and half the other.

Why does the if statement is always the else part even if the if is true?

I'm having a problem with the if statement at the end.
**if the sum of the cubs of the number a user inputs, is equal to the number itself, say "....". Else, say "....." **
The problem is that it always jumps the if part to the else.
Its a task from the uni, no homework or nothing, just training. IF you have suggestions on how to better I would appreciate that too.
Thank you!
{
int n;
cout << "Write a number different from 0 -> ";
cin >> n;
while (n == 0)
{
cout << "Choose another number -> ";
cin >> n;
}
cout << "Good number " << n << " is!" << "\n";
cout << "lets separate each digit:" << "\n" << " -----------------------------------" << endl;
Sleep(1000);
vector<int> vecN;
while (n != 0)
{
int digit = n % 10;
n /= 10;
cout << n << endl;
cout << "Digit: " << digit << endl;
vecN.push_back(digit);
Sleep(750);
}
cout << "There you go!" << endl;
Sleep(1000);
cout << "Next stage, let's find the cubes for each one of the digits!" << endl;
Sleep(2500);
vector<int> sums;
for (auto i = vecN.begin(); i != vecN.end(); i++)
{
Sleep(500);
int Cubes = pow(*i, 3);
cout << Cubes << endl;
sums.push_back(Cubes);
}
Sleep(1300);
cout << "Now let's sum the cubs and see if the number is an Armstrong Number" << endl;
Sleep(3000);
int armSum = accumulate(sums.begin(), sums.end(), 0);
if ( armSum == n )
{
cout << "Sum: " << armSum << endl;
Sleep(500);
cout << "That's an Armstrong Number!" << "\n"
"The sum of the cubs of each digit in the number is equal to that same number!" << endl;
}
else
{
cout << "Sum: " << armSum << endl;
Sleep(500);
cout << "That's not an Armstrong Number!" << endl;
}
return 0;
} ```
When the if-part is entered, the else-part won't be entered any more. Note that your if/else is not surrounded by a loop. So when control passes by once, e.g. when having entered n==0, then it has passed by and won't step into neither the if nor the else-part a second time.
Try something like
while (n==0) {
cout << "Choose another number -> ";
cin >> n;
}
// continue here; n is != 0

Calculation not being done right

I'm fairly new to c++, I have been given an assignment to do a fairly basic program that users can use to buy tickets but I am having some issues with the calculation.
This is my code so far.
#include <iostream>
using namespace std;
int main()
{
double type_ticket, num_tickets, price1, price2, price3, total_price, decision;
cout << "Welcome to the ticket kiosk.";
cout << "\n";
cout << "\n";
cout << "1. VVIP - RM 200";
cout << "\n";
cout << "2. VIP - RM 150";
cout << "\n";
cout << "3. Normal - RM 100" << endl;
cout << "\n";
do
{
cout << "Please select the category of ticket you would like to purchase: ";
cin >> type_ticket;
cout << "\n";
if (type_ticket == 1)
{
cout << "How many would you like: ";
cin >> num_tickets;
cout << "\n";
price1 = num_tickets * 200;
cout << "The price is: RM " << price1 << endl;
cout << "\n";
cout << "\n";
cout << "1. YES" << endl;
cout << "2. NO" << endl;
cout << "\n";
cout << "Would you like to continue purchasing more tickets: ";
cin >> decision;
cout << "\n";
}
else if (type_ticket == 2)
{
cout << "How many would you like: ";
cin >> num_tickets;
cout << "\n";
price2 = num_tickets * 150;
cout << "The price is: RM " << price2 << endl;
cout << "\n";
cout << "\n";
cout << "1. YES" << endl;
cout << "2. NO" << endl;
cout << "\n";
cout << "Would you like to continue purchasing more tickets: ";
cin >> decision;
cout << "\n";
}
else if (type_ticket == 3)
{
cout << "How many would you like: ";
cin >> num_tickets;
cout << "\n";
price3 = num_tickets * 100;
cout << "The price is: RM " << price3 << endl;
cout << "\n";
cout << "\n";
cout << "1. YES" << endl;
cout << "2. NO" << endl;
cout << "\n";
cout << "Would you like to continue purchasing more tickets: ";
cin >> decision;
cout << "\n";
}
else
{
cout << "You have entered an invalid input, please try again. " << endl;
cout << "\n";
}
}
while (decision == 1);
total_price = price1 + price2 + price3;
cout << "The grand total is: RM " << total_price << endl;
cout << "\n";
cout << "Thank you for using this service today, we hope you enjoy the show." << endl;
cout << "\n";
}
The problem that I am having is when the user buys tickets from vvip and/or vip, the calculation for total_price is not being done right. When a price 3 has been entered however, the calculation works fine.
User buys vvip and/or vip = calculation not done right.
User buys normal and vvip and/or vip = calculation done right.
Any help would be very much appreciated.
FYI, this code is not yet complete, but for now, this is what I have.
You seem not to initialize priceN (where N is one of 1, 2, 3) variables before calculation of:
total_price = price1 + price2 + price3;
in case of only one type of the ticket, so the result is unpredictable because variables contain garbage.
You should start with :
double price1 = 0;
double price2 = 0;
double price3 = 0;

Why is this portion of code still executing?

Why is my else, cout << "You have entered an incorrect code" still executing and writing to the screen after I enter r or R and complete the calculation and dialogue. The same does not happen when I enter p or P and follow through with that portion of my program. Sorry for the incredibly nooby question.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
char service;
int number;
int minutes;
int dayMinutes;
int nightMinutes;
double bill;
double dayCharge;
double nightCharge;
double const REG_FEE = 10.00;
double const PREM_FEE = 25.00;
double const REG_MIN = 0.20;
double const PREM_DAY = 0.10;
double const PREM_NIGHT = 0.05;
cout << "Please enter your account number: ";
cin >> number;
cout << "Please enter your service type (regular or premium): ";
cin >> service;
if (service == 'r' || service == 'R')
{
cout << "How many minutes have been used for this service?: ";
cin >> minutes;
if (minutes <= 50)
{
bill = REG_FEE;
cout << fixed << showpoint << setprecision(2);
cout << "Your bill is $" << bill << "." << endl;
cout << "The account number entered was: " << number << "." << endl;
cout << "The service type entered was: " << service << "." << endl;
cout << "You used: " << minutes << " minutes." << endl;
}
else
{
bill = ((minutes - 50) * REG_MIN) + REG_FEE;
cout << fixed << showpoint << setprecision(2);
cout << "Your bill is $" << bill << "." << endl;
cout << "The account number entered was: " << number << "." << endl;
cout << "The service type entered was: " << service << "." << endl;
cout << "You used: " << minutes << " minutes." << endl;
}
}
if (service == 'p' || service == 'P')
{
cout << "How many minutes were used during the day?: ";
cin >> dayMinutes;
cout << "How many minutes were used during the night?: ";
cin >> nightMinutes;
if (dayMinutes > 75)
{
dayCharge = ((dayMinutes - 75) * PREM_DAY);
}
if (nightMinutes > 100)
{
nightCharge = ((nightMinutes - 100) * PREM_NIGHT);
}
bill = dayCharge + nightCharge + PREM_FEE;
cout << fixed << showpoint << setprecision(2);
cout << "Your bill is $" << bill << "." << endl;
cout << "The account number entered was: " << number << "." << endl;
cout << "The service type entered was: " << service << "." << endl;
cout << "You used: " << dayMinutes + nightMinutes << " minutes." << endl;
}
else
{
cout << "You have entered an invalid service code." << endl;
cout << "The account number entered was: " << number << "." << endl;
cout << "The service type entered was: " << service << "." << endl;
}
return 0;
}
That's because you need this-
if (service == 'r' || service == 'R'){
// your code
}
else if(service == 'p' || service == 'P'){
//your code
}
else {
//your code
}
Problem right now with your code is that if you even enter 'r' or 'R', due to if else condition with 'p' or 'P' becomes false and else part gets executed .
That's why you needed to use if - else if format so that for an input only one part is executed.

Infinite loop in my program

Ok, so for my school project we are basically making a menu with 20 max people to enter information and change if need be. Everything was working fine. However, our assignment has us check input for zip code and Account Balance for integer values. I used a do-while loop for ZipCode validation until a positive number and a digit was entered. However, I get an infinite loop that I can't seem to fix. Here is my code. The error lies on lines 57-68 if you put into a compiler. Every time I enter a letter instead of a integer, I get an infinite loop. But I can't figure out why. Thanks!
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>
using namespace std;
struct Account //Structure to be used throughout
{
string CustomerName;
string CustomerAddress;
string City;
string State;
int ZIPCode;
string Telephone;
int AccountBalance;
string DateOfLastPayment;
};
//function prototypes
void valueChangeFunc(string, Account[], int);//This function will be used in option 2 for editing a certain customer information
int main()
{
Account array[20]; //Array to hold up to 20 customers
int choice; //this will hold which option the user decides to make 1-4
bool flagZip = false; //This will be used later on as a flag for a do-while loop
bool flag = false; //This will be used as a flag for the do-while loop right now
int index = 0; //Index for our customers. This tells how many customers have been entered
do //This do while loop will continue to ask the user what option to do until array fills up with 20 people and 4 is not entered
{
cout << "1. Enter new account information \n" <<endl
<< "2. Change account information \n" << endl
<< "3. Display all account information\n" <<endl
<< "4. Exit the program \n" <<endl;
cin >> choice;
if (choice > 4 || choice <= 0)//If user enters a number bigger than 4 or less then or equal to 0. Error!
cout << "Please enter a number between 1 and 4" << endl;
else if(choice == 1)
{
cout << "CustomerName: ";
cin.ignore();
getline(cin, array[index].CustomerName);
cout << "CustomerAddress ";
getline(cin, array[index].CustomerAddress);
cout << "City: ";
getline(cin, array[index].City);
cout << "State: ";
getline(cin, array[index].State);
do
{
cout << "Zip Code: ";
cin >> array[index].ZIPCode;
cin.ignore();
if (!isdigit(array[index].ZIPCode) && array[index].ZIPCode <= 0)
cout << "Please enter a valid entry " << endl;
else
flagZip = true;
}while(flagZip == false);
cout << "Telephone: ";
getline(cin, array[index].Telephone);
flagZip = false;
do
{
cout << "AccountBalance: ";
cin >> array[index].AccountBalance;
cin.ignore();
if (array[index].AccountBalance <= 0)
cout << "Please enter a valid entry " << endl;
else
flagZip = true;
}while(flagZip == false);
cout << "DateOfLastPayment: ";
getline(cin, array[index].DateOfLastPayment);
cout << "\n\nCustomerName: " << array[index].CustomerName << endl;
cout << "CustomerAddress " << array[index].CustomerAddress <<endl;
cout << "City: " << array[index].City << endl;
cout << "State: " << array[index].State << endl;
cout << "Zip Code: " << array[index].ZIPCode << endl;
cout << "Telephone: " << array[index].Telephone <<endl;
cout << "AccountBalance: " << array[index].AccountBalance << endl;
cout << "DateOfLastPayment: " << array[index].DateOfLastPayment << endl;
cout << "You have entered information for customer number " << index << endl << endl;
index++;
}
else if(choice == 2 && index != 0)
{
int num;
string valueChange;
do
{
cout << " Customer number: ";
cin >> num;
if (num > (index-1) || num < 0)
cout << " There is no customer with that number " << endl;
}while (num > (index-1));
cout << "\n\nCustomer Name: " << array[num].CustomerName << endl;
cout << "Customer Address " << array[num].CustomerAddress <<endl;
cout << "City: " << array[num].City << endl;
cout << "State: " << array[num].State << endl;
cout << "ZIPCode: " << array[num].ZIPCode << endl;
cout << "Telephone: " << array[num].Telephone <<endl;
cout << "Account Balance: " << array[num].AccountBalance << endl;
cout << "Date of last payment: " << array[num].DateOfLastPayment << endl;
cout << "You have requested information for customer number " << num << endl << endl;
cout << "What value do you want to change? (press 4 to change 'Date of last payment') \n";
cin.ignore();
getline(cin,valueChange);
valueChangeFunc(valueChange, array, num);
cout << "\nHere is the new value you entered for " << valueChange << endl;
cout << "\n\nCustomer Name: " << array[num].CustomerName << endl;
cout << "Customer Address " << array[num].CustomerAddress <<endl;
cout << "City: " << array[num].City << endl;
cout << "State: " << array[num].State << endl;
cout << "ZIPCode: " << array[num].ZIPCode << endl;
cout << "Telephone: " << array[num].Telephone <<endl;
cout << "Account Balance: " << array[num].AccountBalance << endl;
cout << "Date of last payment: " << array[num].DateOfLastPayment << endl << endl;
}
else if(choice == 3 && index != 0)
{
int num2;
do
{
cout << "Enter the Customer Number to display information regarding that customer" << endl;
cin >> num2;
if (num2 > (index-1) || num2 < 0)
cout << "That Customer does not exist " <<endl;
}
while(num2 > (index-1));
cout << "\n\nCustomerName: " << array[num2].CustomerName << endl;
cout << "CustomerAddress " << array[num2].CustomerAddress <<endl;
cout << "City: " << array[num2].City << endl;
cout << "State: " << array[num2].State << endl;
cout << "Zip Code: " << array[num2].ZIPCode << endl;
cout << "Telephone: " << array[num2].Telephone <<endl;
cout << "AccountBalance: " << array[num2].AccountBalance << endl;
cout << "DateOfLastPayment: " << array[num2].DateOfLastPayment << endl;
cout << "You have entered information for customer number " << index << endl << endl;
}
else
flag = true;
}while (flag == false);
return 0;
}
void valueChangeFunc(string valueChange2, Account array[], int num)
{
if (valueChange2 == "Customer Name" || valueChange2 == "Customer name" || valueChange2 == "customer Name" || valueChange2 == "customer name")
{
cout << "\nEnter new value for Customer Name: " <<endl;
getline(cin, array[num].CustomerName);
}
if (valueChange2 == "Customer Address" || valueChange2 == "Customer address" || valueChange2 == "customer Address" || valueChange2 == "customer address")
{
cout << "\nEnter new value for Customer Address: " <<endl;
getline(cin, array[num].CustomerAddress);
}
else if(valueChange2 == "city" || valueChange2 == "City")
{
cout << "\nEnter new value for City: " << endl;
getline(cin, array[num].City);
}
else if(valueChange2 == "state" || valueChange2 == "State")
{
cout << "Enter a value for State: " << endl;
getline(cin,array[num].State);
}
else if(valueChange2 == "Zip Code" || valueChange2 == "zip Code" || valueChange2 == "Zip code" || valueChange2 == "zip code")
{
cout << "\nEnter a value for Zip Code: " << endl;
cin >> array[num].ZIPCode;
}
else if(valueChange2 == "telephone" || valueChange2 == "Telephone")
{
cout << "\nEnter a value for Telephone: " << endl;
getline(cin, array[num].Telephone);
}
else if(valueChange2 == "Account Balance" || valueChange2 == "Account balance" || valueChange2 == "account Balance" || valueChange2 == "account balance")
{
cout << "\nEnter a value for account balance: " << endl;
cin >> array[num].AccountBalance;
}
else if(valueChange2 == "4")
{
cout << "\nEnter the value for Date of last payment: " << endl;
getline(cin, array[num].DateOfLastPayment);
}
else
cout << "Not entered correctly. Please enter a valid entry to edit " << endl;
}
Again everything worked until I started to use a loop to check for digit value of ZipCode. The loop only goes infinite when I enter a letter. It works for a negative number and positive number.
Short answer can be found in cplusplus.com (read the third paragraph)
Long answer:
This error isn't about ZipCode only, you can generate the same error when you input a letter instead of a number at the very first cin call.
cin is not type-safe so using a wrong type as an input results in an undefined behaviour (like the infinite loop you were experiencing) and that is why cin is a bit prone to errors. Also, cin gets the input value, however it doesn't remove newline, reading to a bit dirtier input from what you'd get with other methods.
Speaking of other methods, as explained in the link, try to use getline() whenever it is possible. You can use that function to get what cin buffer contains as a string and do additional type-check if necessary. Bug-free programs are more important than shorter programs.
As a personal note: try to use while loops instead of do..while ones when you can. That is not a general rule of programming but it looks more readable and is easier to understand in general (IMHO).
Also, try to use functions to split your program into parts. For example, the cout blocks where you are just printing the information stored to the screen can be turned into a function. You're using the same cout structure (it would shorten your code by 4 * 9 lines).
Finally, if you're using an integer as a key value to separate algorithms, try to use switch...case instead of if-else blocks. (Again, just my opinion).