I have a question that should be simple but I can't find the answer anywhere.
I have a menu driven C++ program that works perfectly when the menu options are numbers but I can't figure out how to change the numbers to letters.
For example:
works fine when choices are 1, 2, or 3 but not A, B, C.
Not sure how I am supposed to declare the option... is it a char? thanks in advance
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
//Variables needed for the problem
int numbServCharge; //number of service charges
char choice; //menu choice
double transAmt, balence, totalServCharge; //transaction amount, current balence, total service charges
//Constant service change
const double servCharge = 0.25; //constant $0.25 for service charges
numbServCharge = 0; //Start the counter for number of service charges at zero
cout << "Checkbook Balencing Program\n\n";
cout << "Enter the beginning balence: ";
cin >> balence; //get the initial balence
cout << endl;
do
{
//Highlight menu options
cout << "\nCommands\n";
cout << "C - process a check\n";
cout << "D - process a deposit\n";
cout << "E - end the program\n\n";
//Get user's choice from menu
cout << "Enter transaction type: ";
cin >> choice;
cout << endl;
//Create an error message for invalid choice and get a second choice
while((choice != 'C') && (choice != 'D') && (choice != 'E')
{
cout << "Invalid selection. Please choose C, D or E: ";
cin >> choice;
}
//Set up for option #1 -- using a check
if(choice=='C')
{
cout << "Enter transaction amount: ";
cin >> transAmt; //Get the amount of the check
cout << "\nProcessing check for $" << fixed << setprecision(2) << transAmt;
transAmt = transAmt + servCharge; //Add the service charge onto the transaction
numbServCharge++; //Add one to the number of service charges there have been
balence = balence - transAmt; //Update account balence
cout << "\nBalence: $" << fixed << setprecision(2) << balence;
cout << "\nService charge: $0.25 for a check\n";
totalServCharge = servCharge * numbServCharge; //Update total cost of service charges
cout << "Total service charges: $" << fixed << setprecision(2) << totalServCharge << endl; //Tell user total service charges so far
}
//Set up for option #2 -- deposits
if(choice=='D')
{
cout << "Enter transaction amout: ";
cin >> transAmt; //Get the amount of the deposit
cout << "\nProcessing Deposit for $" << fixed << setprecision(2) << transAmt << endl;
transAmt = transAmt - servCharge; //Add the service charge onto the deposit
numbServCharge++; //Add one to the number of service charges there have been
balence = balence + transAmt; //Update account balence
cout << "Balence: $" << fixed << setprecision(2) << balence << endl;
totalServCharge = servCharge * numbServCharge; //Update total cost of service charges
cout << "Total service charges: $" << fixed << setprecision(2) << totalServCharge << endl; //Tell user total service charges so far
}
}while(choice != 'E'); //Close program if option 3 is selected
//Display final balence
cout << "Processing end of the month";
cout << "\nFinal balence : $ " << fixed << setprecision(2) << balence << endl << endl;
system("pause"); //Pause screen so it doesn't close right away
return 0;
}
When testing for a string, you should convert everything to a common case. In you case you should convert the user input to upper case. You can do this by using toupper function
Here is the bit of code you need to change to make your program work
cout << "Enter transaction type: ";
cin >> choice;
choice = toupper(choice); // Change Here
cout << endl;
Once you change while((choice != 'C') && (choice != 'D') && (choice != 'E') to while((choice != 'C') && (choice != 'D') && (choice != 'E')), your code runs well. Although I would have personally used a std::string instead of a char.
Granted, Caesar's answer is a valid point - and I would change that as well. However, it would be better as a comment because it doesn't resolve the problem. Wait, hold on. What problem? Your program seems to still "run perfectly" even with the alphabetic menu options.
The only bug in your program is when you try and assign balence (or any of your three doubles) to a non-numeric entry. When I type "C" for initial balance, I see this monstrosity:
Over and over and over. That's not fun. Similar thing happens if I type a letter for transaction amount:
Solution: Never try to jam input taken directly from the user into a variable that is not a type of string. Use a built in string-to-number function like atof, or (much preferred) add error handlers like this:
if (std::cin >> dbl)
{
//input is a double. handle that here.
}
else
{
//input isn't a double. handle that here.
}
By the way, it's spelled balance, not balence ;)
Related
I am having difficulty locating and solving a bug in my basic ATM program. The issue manifests in the withdrawal option of both the checking and savings accounts. After the account has zero available funds it will allow the user to enter a negative number essentially over-drafting the account. I am trying to prevent this from happening.
Additionally, if there are zero funds available to withdraw the program continues to loop, thereby not allowing the user to utilize the menu to select a different option.
I have provided examples of the screen output illustrating the issues and the some of the source code.
Issue
Issue
#include <iomanip>
#include <iostream>
using std::cin;
using std::cout;
double checking_balance = 2500.00, savings_balance = 1000.00, savings_amount,
checking_amount;
int menu;
int main() {
do {
// Main Menu
cout << std::fixed << std::setprecision(2);
cout << "\n";
cout << "\tWelcome to Seabreeze Bank\n";
cout << "*********************************\n\n";
cout << "1. Savings Account\n";
cout << "2. Checking Account\n";
cout << "3. Quit\n\n";
cin >> menu;
cout << "\n\n";
// User validation for the Main Menu
if (menu < 1 || menu > 3) {
cout << "You have entered an invalid option.\n";
cout << "Please enter a number 1-3 > ";
cin >> menu;
cout << "\n\n";
}
switch (menu) {
case 1:
int savings_menu;
do {
// Savings Account Menu
cout << "\t\tSavings Account\n\n";
cout << "Please enter a menu item (1-3) >\n";
cout << "*********************************\n";
cout << "1. Withdrawal\n";
cout << "2. Deposit\n";
cout << "3. Main Menu\n";
cout << "\n\n";
cin >> savings_menu;
cout << "\n";
// Withdrawal selection for Savings Account
if (savings_menu == 1) {
cout << "How much would you like to withdraw from your savings "
"account: ";
cin >> savings_amount;
cout << "\n";
while (savings_balance < savings_amount) {
cout << "You do not have enough funds in your account to withdraw "
"that much\n";
cout << "Please enter a smaller amount: ";
cin >> savings_amount;
cout << "\n";
}
while (savings_amount <= 0) {
cout << "Please enter an amount greater than 0: ";
cin >> savings_amount;
}
savings_balance -= savings_amount;
cout << "Your Savings Account Balance: " << savings_balance << "\n\n";
if (savings_balance == 0) {
cout << "You now have zero funds in your Savings Account.\n\n";
}
}
This is a floating point arithmetic problem.
In general, floating point arithmetic is not exact because of rounding errors, saving_amount is not equal to 0 but it is almost equal to 0.
I prefer the casting option because in certain cases using the round() function will need a bit more modification if the result is negative.
Instead of "while (savings_amount <= 0)" you should use while (int(saving_amount) <= 0). Similarly you have to do casting where you are using conditional operator in your program.
To prevent entering negative number to withdraw, you have to put an "if" statement to check if number is negative.
I have an assignment for my intro C++ class to make a program that has a user select C, D, or E to process a check, deposit a check, or end the program respectively. The professor specified that if a user chooses C or D, he would like to accept both the selection and the amount of money in the same line. For example, if a user wants to deposit a check for $20, they would enter "D 20" in one line. I have it set up as such:
cout << "Enter the beginning balance:\n\n";
cin >> balance;
cout << "Commands:\n";
cout << "C - process a check\n";
cout << "D - process a deposit\n";
cout << "E - end the program\n\n";
while (choice != 'E')
{
cout << "Enter a transaction:\n";
cin >> choice >> amount;
Followed by a switch statement. The code itself works properly when entering C or D, but when I go to enter E to end the program, it will only work if I add a number to the end, because the line asking for input wants a char and a float. However, in the example output my professor showed, you could just enter E and it would terminate. Is there any way around this? How can I set it up so it accepts E differently from C and D?
EDIT: Here is the switch statement:
switch(choice)
{
case 'C':cout << fixed << setprecision(2);
cout << "Processing check for $" << amount << endl;
balance = processCheck(amount, balance);
cout << "Balance: $" << balance << endl;
break;
case 'D':cout << fixed << setprecision(2);
cout << "Processing deposit for $" << amount << endl;
balance = depositCheck(amount, balance);
cout << "Balance: $" << balance << endl;
break;
case 'E':cout << "Processing end of month\n";
cout << "Final balance: $" << balance << endl;
break;
default : cout << "Invalid choice\n";
}
Already answered in comments, but anyway:
Replace this code
cin >> choice >> amount;
by gradual and conditional input code:
cin >> choice;
if (choice == 'C' || choice == 'D')
cin >> amount;
I am writing a program that simulates an ATM. So it tracks account balances, withdrawals and deposits in a very basic matter.
Everything works well during the first iteration, but if I go to make two or more deposits or withdrawals, the account balances default back to the original amount.
Here is an example of what is currently happening: I have $1,000 in my account initially. I make a deposit of $50. It prints out that I now have $1,050 in my account and asks if I would like to perform any other actions. (This is all good). If I select that I want to make another deposit of $100, it says my new account balance is $1,100 instead of $1,150. It does not store my latest account balance when I perform new withdrawals or deposits.
The second (less important) issue is that each time a withdrawal is made, there is a $2.50 fee for each withdrawal that also gets subtracted from my account balance.
I have not learned loops yet, only Cases, If statements and If Else Statements.
Is it possible to do what I want to do? Below is my code. Thank you in advance! This is my first time posting, so if I have pasted my code wrong, I apologize.
#include <iostream>
#include <string>
using namespace std; // opens library for "cout"
int main()
{
float test;
int logout;
string name;
float balance;
float fee;
int choice;
float withdraw;
float deposit;
float bonus;
bonus = 2.50;
balance = 1572.36;
fee = 12.50;
char answer;
cout << "Hello, thank you for banking with Pallet Town Bank.\n";
cout << "Please enter your name. ";
cin >> name;
cout << "Hello " << name << ". Your current balance is $" << balance << ".\n";
cout << "There will be a a service fee of $12.50 subtracted from your "
"account.\n";
cout << "Your updated balance will be $" << balance - fee << " \n";
cout << "What would you like to do today?\n";
do
{
cout << "\n1 - Current Balance\n2 - Withdraw\n3 - deposit\n4 - Log "
"Out\nOption: ";
cin >> choice;
switch (choice)
{
case 1:
cout << "\nCurrent Balance is " << balance - fee - withdraw + deposit
<< " \n";
cout << "Would you like to take any other actions today?\n";
break;
case 2:
cout << "\nWithdraw - How much would you like to withdraw? $";
cin >> withdraw;
cout << "Your new balance after withdrawing $" << withdraw << " will be $"
<< balance - fee - withdraw + deposit << "\n";
cout << "Would you like to take any other actions today?\n";
break;
case 3:
cout << "\nDeposit - How much would you like to deposit? $";
cin >> deposit;
test = balance - fee - withdraw + deposit;
cout << "Your new balance after depositing $" << deposit << " will be $"
<< test << endl; //<<balance - fee - withdraw + deposit<<"\n";
cout << "Would you like to take any other actions today? Y or N \n";
cin >> answer;
cout << answer;
if (answer == 'y' || 'Y')
{
test = balance - fee - withdraw + deposit + deposit;
cout << "Your new balance after depositing $" << deposit << " will be $"
<< test << endl;
}
// cout <<"Your new balance after depositing $"<<deposit<<" will be $"
// <<test<< endl; //<<balance - fee - withdraw + deposit<<"\n";
// cout <<"Would you like to take any other actions today?\n";
break;
case 4:
cout << "\nLog Out - Thank you for banking with Pallet Town Bank. Have "
"a great day!";
}
} while (choice != 4);
}
The main issue, as Alan Birtles points out, is that you never update the balance value; you just store the temporary calculations in the test variable.
Here's how you could change your code. I tried interpreting the expected behaviour of the program as best I could from the text:
#include <iostream>
#include <string>
using namespace std;
int main()
{
const double fee = 12.50;
double balance = 1572.36;
cout << "Hello, thank you for banking with Pallet Town Bank.\n";
cout << "Please enter your name. ";
string name;
cin >> name;
cout << "Hello " << name << ". Your current balance is $" << balance << ".\n";
cout << "There will be a a service fee of $12.50 subtracted from your "
"account.\n";
cout << "Your updated balance will be $" << (balance -= fee) << " \n";
cout << "What would you like to do today?\n\n";
while (true)
{
cout << "1 - Current Balance" << '\n'
<< "2 - Withdraw" << '\n'
<< "3 - deposit" << '\n'
<< "4 - Log Out" << '\n'
<< "Option: ";
int choice;
cin >> choice;
cout << endl;
if (choice == 4) break;
switch (choice)
{
case 1:
cout << "Current Balance is " << balance << '\n';
break;
case 2:
cout << "Withdraw - How much would you like to withdraw? $";
double withdraw;
cin >> withdraw;
cout << "Your new balance after withdrawing $" << withdraw << " will be $"
<< (balance -= withdraw) << '\n';
break;
case 3:
cout << "Deposit - How much would you like to deposit? $";
double deposit;
cin >> deposit;
cout << "Your new balance after depositing $" << deposit << " will be $"
<< (balance += deposit) << '\n';
break;
}
cout << "Would you like to take any other actions today? ";
char answer;
cin >> answer;
cout << endl;
if (toupper(answer) == 'N') break;
}
cout << "Log Out - Thank you for banking with Pallet Town Bank. Have a great day!" << endl;
}
Live demo
Changes
First of all, every time a modification is made (withdrawal/deposit), we need to actually update the balance. We can do so by using the += or -= operators (called "compound assignment" operators): when writing balance += x, we're adding x to balance, and when writing balance -= x we're subtracting. These expressions are equivalent to balance = balance + x and balance = balance - x, respectively.
I moved the "Would you like to [...]" part outside the switch statement, to avoid repeating it in each case.
As pointed out in the comments, answer == 'Y' || 'y' isn't the same as answer == 'Y' || answer == 'y'. I changed that to toupper(answer) == 'Y'.
I moved the logout handling outside the while loop, so that whenever the loop terminates, the logout message is always shown. That allows us to remove case 4 from the switch statement, by checking at the beginning if choice == 4 and then breaking out of the loop accordingly. This also implies the loop becomes a while (true) loop. Probably there is a more elegant way.
Even better
If you're confortable with functions, I would suggest refactoring the code, isolating each operation individually:
#include <iostream>
#include <string>
#include <sstream>
#include <cmath>
using namespace std;
const int FEE = 1250; // fee in cents
//---- Utilities ----//
string moneyString(int cents) {
ostringstream oss;
oss << cents/100 << '.' << cents % 100;
return oss.str();
}
int toCents(double money) {
return int(round(money*100));
}
int getMoney() {
double money;
cin >> money;
return toCents(money);
}
//---- User input ----//
// Available choices
enum Choices {
BALANCE = 1,
WITHDRAW = 2,
DEPOSIT = 3,
LOGOUT = 4
};
short int getChoice() {
short int choice = 0;
while (choice < 1 or choice > 4) {
cout << "1 - Current Balance" << '\n'
<< "2 - Withdraw" << '\n'
<< "3 - deposit" << '\n'
<< "4 - Log Out" << '\n'
<< "Option: ";
string input;
cin >> input;
choice = atoi(input.c_str());
cout << endl;
}
return choice;
}
bool userWantsMoreActions() {
cout << "Would you like to take any other actions today? ";
char answer;
cin >> answer;
cout << endl;
return toupper(answer) == 'Y';
}
//---- Actions ----//
void greeting(double &balance) {
cout << "Hello, thank you for banking with Pallet Town Bank.\n";
cout << "Please enter your name. ";
string name;
cin >> name;
cout << "Hello " << name << ". Your current balance is $" << moneyString(balance) << ".\n";
cout << "There will be a a service fee of $12.50 subtracted from your account.\n";
cout << "Your updated balance will be $" << moneyString(balance -= FEE) << " \n";
cout << "What would you like to do today?\n\n";
}
void printBalance(const double &balance) {
cout << "Current Balance is " << balance << '\n';
}
void withdraw(double &balance) {
cout << "Withdraw - How much would you like to withdraw? $";
int withdraw = getMoney();
cout << "Your new balance after withdrawing $" << withdraw << " will be $"
<< (balance -= withdraw -= FEE) << '\n';
}
void deposit(double &balance) {
cout << "Deposit - How much would you like to deposit? $";
int deposit = getMoney();
cout << "Your new balance after depositing $" << moneyString(deposit)
<< " will be $" << moneyString(balance += deposit -= FEE) << '\n';
}
int main()
{
// Initialize a sample session:
double balance = 157236;
greeting(balance);
while (true)
{
short int choice = getChoice();
if (choice == Choices::BALANCE) printBalance(balance);
else if (choice == Choices::WITHDRAW) withdraw(balance);
else if (choice == Choices::DEPOSIT) deposit(balance);
else if (choice == Choices::LOGOUT) break;
if (not userWantsMoreActions()) break;
}
cout << "Log Out - Thank you for banking with Pallet Town Bank. Have a great day!" << endl;
}
Live demo
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I've been writing an assignment where we're tasked with making a shopping cart program that tracks the customer's cumulative price.
I'm not allowed to use strings, global variables, or user defined functions
I'm strictly instructed to use only Character arrays and loops.
While my shopping cart program works fine, I was wondering if there is any way to simplify my code? I feel like I would be penalized for making the code overly complicated. I feel like my quit feature in particular is overly complicated. Is there a better, simpler way of implementing it without using strings or functions?
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
char continueOrQuit;
char productName[900];
float productPrice;
float totalCost = 0;
int productQuantity = 0;
bool validResponse;
cout << "Welcome to SmartCart" << endl;
cout << "Simply enter the name of your product when prompted" << endl;
cout << "After you enter your product, enter the price when prompted \n\n";
//while ((productName[900] != 'D', 'o', 'n', 'e') || (productName[900] != 'd', 'o', 'n', 'e'))
//While im not done shopping
do
{
cout << "Name of Product: "; // Prompt for product
cin.getline(productName, 900); // Get the name
cout << endl;
cout << "Cost of Product: "; // Prompt for product cost
cin >> productPrice; // Get the cost
while ((!cin) || (productPrice < 0))
{
cout << "Invalid Input!! Try again!!" << endl << endl;
cout << "Cost of Product: "; // Prompt again for product cost
cin.clear();
cin.ignore(100, '\n');
cin >> productPrice;
}
cin.ignore(250, '\n'); // Ignore the rest of the garbage
cout << endl;
// if everything is correct, we set up the display and give the results.
cout.setf(ios::fixed, ios::floatfield);
cout.setf(ios::showpoint);
cout.precision(2);
cout << "The item(s) \"" << productName << "\" has/have been added to your cart for $"
<< productPrice << endl;
totalCost = totalCost + productPrice; // Calculating the cumulative sum total
cout << "Your shopping total so far is: $" << totalCost << endl; // Display the sum total
productQuantity++; // Count the number of items in cart
cout << "You have " << productQuantity << " item(s) in your cart." << endl;
// Display the amount of characters in the cart
cout << "To quit shopping, type \"Q\". Otherwise, type \"C\" (Without quotation marks)"
<< endl;
cout << "Would you like to continue shopping? (C/Q) : ";
cin >> continueOrQuit;
cin.ignore(100, '\n');
continueOrQuit = tolower(continueOrQuit);
if (continueOrQuit == 'q')
{
cout << "You have chosen to finish and check out." << endl;
validResponse = true;
}
else if (continueOrQuit == 'c')
validResponse = true;
else
cout << "You have to type either C or Q!" << endl;
validResponse = false;
while (!validResponse)
{
cout << "Would you like to continue shopping? (C/Q) : ";
cin >> continueOrQuit;
cin.ignore(100, '\n');
continueOrQuit = tolower(continueOrQuit);
if (continueOrQuit == 'q')
{
cout << "You have chosen to finish and check out." << endl;
validResponse = true;
}
else if (continueOrQuit == 'c')
validResponse = true;
}
} while (continueOrQuit == 'c');
cout << "Your checkout total is $" << totalCost << endl;
cout << "You are purchasing a total of " << productQuantity << endl;
system("PAUSE");
return 0;
}`
Here a shorter version of your code.
mainly I removed extra code when you check input by putting a do while so the case of wrong input the re-input go back to the first try.
You also have a missing bracket in the last else, it cause you to re-enter q or c in case you already enter it correctly.
Here is the code, you can compare to the original.
int main()
{
char continueOrQuit;
char productName[900];
float productPrice;
float totalCost = 0;
int productQuantity = 0;
bool validResponse;
cout << "Welcome to SmartCart" << endl;
cout << "Simply enter the name of your product when prompted" << endl;
cout << "After you enter your product, enter the price when prompted \n\n";
do
{
cout << "Name of Product: "; // Prompt for product
cin.getline(productName, 900); // Get the name
cout << endl;
do{
cout << "Cost of Product: "; // Prompt for product cost
cin >> productPrice; // Get the cost
if(!cin || productPrice < 0){
cout << "Invalid Input!! Try again!!" << endl << endl;
cin.clear();
cin.ignore(100, '\n');
}
}while ((!cin) || (productPrice < 0));
cin.ignore(250, '\n'); // Ignore the rest of the garbage
cout << endl;
// if everything is correct, we set up the display and give the results.
cout.setf(ios::fixed, ios::floatfield);
cout.setf(ios::showpoint);
cout.precision(2);
cout << "The item(s) \"" << productName << "\" has/have been added to your cart for $"
<< productPrice << endl;
totalCost = totalCost + productPrice; // Calculating the cumulative sum total
cout << "Your shopping total so far is: $" << totalCost << endl; // Display the sum total
productQuantity++; // Count the number of items in cart
cout << "You have " << productQuantity << " item(s) in your cart." << endl;
// Display the amount of characters in the cart
do{
cout << "To quit shopping, type \"Q\". Otherwise, type \"C\" (Without quotation marks)"
<< endl;
cout << "Would you like to continue shopping? (C/Q) : ";
cin >> continueOrQuit;
cin.ignore(100, '\n');
continueOrQuit = tolower(continueOrQuit);
if(continueOrQuit == 'q' || continueOrQuit == 'c')
validResponse = true;
else
{
cout << "You have to type either C or Q!" << endl;
validResponse = false;
}
}while(!validResponse);
if (continueOrQuit == 'q')
{
cout << "You have chosen to finish and check out." << endl;
}
} while (continueOrQuit == 'c');
cout << "Your checkout total is $" << totalCost << endl;
cout << "You are purchasing a total of " << productQuantity << endl;
system("PAUSE");
return 0;
}
My assignment is use 3 functions with parameters, as follows:
function calcRegBill – accepts one integer argument for the number of minutes used. Determines and returns the total amount due.
function calcPremBill – accepts two integer arguments, for the number of day minutes and number of night minutes used. Determines and returns the total amount due.
function printBill – accepts 4 arguments: a string account number, a character service code, an integer total number of minutes used, and an amount due. Note that this is a generic print bill function, which prints either a regular or premium bill, using the following format:
Account Number: XXXX
Service Type: Regular (or Premium, depending on the character received)
Total Minutes: XXX
Amount Due: $XXX.XX
Your main function will prompt the user for the account number and service code. Based on the service code, main will ask for the correct number of minutes, then call your functions above as needed to finish the job. In addition you must :
Incorporate a loop in your program to run the bill as many times as needed. You may do this either by a sentinel controlled loop, or with a counter controlled loop.
I already built the program and tested it with everything in the main function of the program. I am just really confused about how to break it into the 3 separate functions and have it all still work. I am a total noob at C++
Here is the program so far, I started to add the functions, but I do not believe they're right.
// Cell Bill Fun
// April 14, 2013
#include <iostream>
#include <iomanip>
using namespace std;
double calcRegBill(int a);
double calcPremBill(int b, int c);
void printBill(string acctNumber, char serviceCode, int d, double e);
int main()
{
//declare variables for question 4
char serviceCode;
int acctNumber;
int minutes;
int dayMinutes;
int nightMinutes;
int charge;
int dayFee;
int nightFee;
double amtDue;
//get input
cout << "Please enter your information to calculate your cell phone bill ";
cout << "What is your account number? (please enter a 4-digit number-example 1234): ";
cin >> acctNumber;
cout << "Do you have regular or premium service? Enter r for regular service, p for Premium.: ";
cin >> serviceCode;
//format output
cout<< setprecision(2) << fixed;
//output
switch (serviceCode)
{
case 'r':{
cout << "How many minutes did you use?: ";
cin >> minutes;
if (minutes <= 50)
amtDue = 10;
else if (minutes > 50)
amtDue=10+((minutes-50)*.20);
else
cout <<"You have input an invalid service code. Please type r for regular or p for premium service." << endl;
cout <<"Cellular Account #:" << acctNumber << endl;
cout <<"Type of Service: Regular" << endl;
cout <<"Total Minutes:" << minutes << endl;
cout <<"Amount Due: $"<< amtDue << endl;}
break;
case 'R':{
cout << "How many minutes did you use?: ";
cin >> minutes;
if (minutes <= 50)
amtDue = 10;
else if (minutes > 50)
amtDue=10+((minutes-50)*.20);
else
cout <<"You have input an invalid service code. Please type r for regular or p for premium service." << endl;
cout <<"Cellular Account #:" << acctNumber << endl;
cout <<"Type of Service: Regular" << endl;
cout <<"Total Minutes:" << minutes << endl;
cout <<"Amount Due: $"<< amtDue << endl;}
break;
case 'p':
cout << "How many daytime minutes did you use?";
cin >> dayMinutes;
if (dayMinutes <= 75)
dayFee = 0;
else if (dayMinutes > 75)
dayFee=((dayMinutes-75)*.10);
cout << "How many night time minutes did you use?";
cin >> nightMinutes;
if (nightMinutes <= 100)
nightFee = 0;
else if (nightMinutes > 100)
nightFee=((nightMinutes-100)*.05);
else
cout <<"You have input an invalid service code. Please type r for regular or p for premium service." << endl;
cout <<"Cellular Account #:" << acctNumber << endl;
cout <<"Type of Service: Premium" << endl;
cout <<"Total Minutes:" <<dayMinutes+nightMinutes << endl;
cout <<"Amount Due: $"<<25<<"+"<<dayFee<<"+"<<nightFee<<"= $"<<25+dayFee+nightFee << endl;
break;
case 'P':
cout << "How many daytime minutes did you use?";
cin >> dayMinutes;
if (dayMinutes <= 75)
dayFee = 0;
else if (dayMinutes > 75)
dayFee=((dayMinutes-75)*.10);
cout << "How many night time minutes did you use?";
cin >> nightMinutes;
if (nightMinutes <= 100)
nightFee = 0;
else if (nightMinutes > 100)
nightFee=((nightMinutes-100)*.05);
else
cout <<"You have input an invalid service code. Please type r for regular or p for premium service." << endl;
cout <<"Cellular Account #:" << acctNumber << endl;
cout <<"Type of Service: Premium" << endl;
cout <<"Total Minutes:" <<dayMinutes+nightMinutes << endl;
cout <<"Amount Due: $"<<25<<"+"<<dayFee<<"+"<<nightFee<<"= $"<<25+dayFee+nightFee << endl;
break;
default:
cout << "Invalid Service Code. Enter r for regular service, p for Premium.";
}
return 0;
}
double calcRegBill(int a)
{
}
double calcPremBill(int b, int c)
{
}
void printBill(string acctNumber, char serviceCode, int d, double e )
{
return;
}
Functions work by requesting data (the parameters you pass to them), and operating on this data, often by returning data.
For example, in the case 'r': block, instead of of your code, you would want to have:
cout << "How many minutes did you use?: ";
cin >> minutes;
amtDue = calcRegBill(minutes);
cout <<"Cellular Account #:" << acctNumber << endl;
cout <<"Type of Service: Regular" << endl;
cout <<"Total Minutes:" << minutes << endl;
cout <<"Amount Due: $"<< amtDue << endl;}
break;
Then, you can move the code that was previously in main to calculate amtDue into the calcRegBill() function, like this:
double calcRegBill(int minutes)
{
double bill;
if (a < 50)
bill = 10;
else
bill = 10+((minutes-50)*.20);
return bill;
}
The key here is that instead of calculating amtDue in the main function, you calculate it in the calcRegBill function and return it to the main function. Also, notice that I changed the name of the parameter from a to minutes. This improves clarity of its purpose in the function.
The general structure of your program is mostly correct, and I am not really sure what you are asking.
For trouble shooting, write one of your functions and test it without all the other stuff. For example, write calcRegBill...
Then write a very simple main:
int main() {
cout << calcRegBill(3) << endl;
cout << calcRegBill(11) << endl;
}
Did you get the values expected? If so then move on to the next function. Development is often about breaking the problem down into smaller manageable problems.
You need to break down the flow of what you're doing.
First, you gather information. Note: The information you're looking for is the same, regardless of whether it's a premium or regular bill. You don't need to branch so early.
In order to calculate their bill, you branch based on premium or regular. Either way, you get back a double from this, so you can have a double variable that you store the return from calcRegBill or calcPremBill into. Declare this double variable before the branch, assign to it inside of your two branches (regular or premium).
Then, when you call printBill, you can pass this value and what type of bill it was.