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.
Related
ask how many expenses they have for the month. Loop (using a for-loop) for each of these expenses, asking how much they spent on each one. Numbering for expenses should display for the user starting at one. Keep a running track of how much they're spending as you're looping.
For each expense, verify that the expense costs at least $0.01 in a loop (using a while-loop).
They shouldn't be able to move on until they've entered in a valid expense.
Here is the code shown below. when I input 0 just to see if the while loop works, it doesn't work. Any suggestions?
int main()
{
// Variables //
double monthlyIncome, monthlySave, monthlyBudget, ex_cost = 0.01, ex_num;
int expenseMonth;
// A warm welcome message//
cout << "Welcome to the budget calculator" << endl;
// user puts in monthly income and how much they would like to save//
cout << "Please enter your starting monthly income: ";
cin >> monthlyIncome;
cout << "Please enter how much you would like to save: ";
cin >> monthlySave;
//Calculating and outputting monthly budget//
monthlyBudget = monthlyIncome - monthlySave;
cout << "Your monthly budget is: $" << monthlyBudget << endl;
// user inputs expense number //
cout << "How many expenses did you have this month: ";
cin >> expenseMonth;
// loop for expenses //
for (int i = 1; i <= expenseMonth; ++i) {
cout << "How much did you spend on expense " << i << ":" <<endl;
cin >> ex_num;
while (ex_num <= 0.01) {
cout << "you must have spent at least 0.01 for it to be an expense!" << "Please try again" << endl;
}
}
Your while loop is checking the same expense value over and over without giving the user a chance to change the value if it is not valid, thus it gets stuck in an endless loop.
Also, you are not allowing expenses to be at least 0.01 like the instructions ask for.
Try this instead:
for (int i = 1; i <= expenseMonth; ++i) {
cout << "How much did you spend on expense " << i << ":" <<endl;
cin >> ex_num;
while (ex_num < 0.01) { // <-- needs to be < not <= !
cout << "you must have spent at least 0.01 for it to be an expense! Please try again" << endl;
cin >> ex_num; // <-- add this!
}
}
Personally, I would use a do..while loop instead, since the input has to be read in at least 1 time, eg:
for (int i = 1; i <= expenseMonth; ++i) {
do {
cout << "How much did you spend on expense " << i << ":" <<endl;
cin >> ex_num;
if (ex_num >= 0.01) break;
cout << "you must have spent at least 0.01 for it to be an expense! Please try again" << endl;
}
while (true);
}
I have not done so well on an assignment for school - I have submitted what is below and I would like to learn and understand more about why my code is terrible lol.
The grading criteria is here
As you can tell, I did not do well at all. I am getting a few errors all related to error C2064: term does not evaluate to a function taking 3 arguments. One of the requirements is using pass by reference. When I attempted that, I had many more errors - so I decided to take it back to something a bit simpler for me and I still cannot see what I am doing wrong.
My instructor specified which parameters we needed to use so I am using those specific ones for each function. The other criterion in writing is below as well as my code.
Again, yes this was for a school assignment, I've already submitted it and got a terrible grade. I would like to have an understanding of what I did wrong and how to correct it so I can learn. Thank you for any and all help.
The weekly gross pay of a salaried employee is calculated by dividing
the employee’s annual salary by 52. Create a named constant variable
to hold and use the value in your overloaded function.
• The weekly gross pay of an Hourly employee is calculated as follows:
If the number of hours worked by the employee is 40 hours or less,
the gross pay is calculated by multiplying the number of hours worked
by the pay rate. If the number of hours worked by the employee
exceeds 40 hours, the employee will receive regular pay for the first
40 hours, and receive time-and-a-half pay for the hours in excess of
40. An hourly employee must not work more than 50 hours per week.
• The weekly gross pay of an intern is calculated by multiplying the
number of hours worked by the pay rate. If an intern works over 15
hours a week, the intern receives time-and-a-quarter pay for the
hours over 15 hours. An intern must not work more than 20 hours per
week.
• The weekly gross pay of a contract employee is calculated by
multiplying the number of hours worked by the pay rate. A contract
employee must not work more than 40 hours per week.
Create four overloaded functions (one each for salaried employee,
hourly employee, contract employee, and Intern) as follows:
For the Salaried employee function, prompt for two values (employee
number and yearly salary), and pass these two values to the
appropriate function.
For the Hourly employee function, prompt for three values (employee
number, hours worked and pay rate), and pass these three values to the
appropriate function.
For the Intern function, prompt for four values (Institution Code,
Department Code, hours worked and pay rate), and pass these four
values to the appropriate function.
• For the Contract employee function, prompt for five values (company
number, project number, employee number, hours worked and pay rate),
and pass these five values to the appropriate function.
For any employee, if more hours than the employee is allowed to work
(based on the type of employee) is entered for number of hours,
reject the input as invalid input, and repeatedly prompt for the valid
range of hours for the employee type until the correct information is
entered.
Continue to request, calculate and display employee information until
there is no more employee data to process. The information displayed
must include all the information collected for each employee and the
calculated weekly pay. Use the end-of-file indicator to terminate
input.
Your program must be able to process zero employees, to an infinite
number of employees. When the program starts, if there is no data to
process during this processing cycle, immediately use the end-of-file
indicator to terminate processing, and display an appropriate
message.
Demonstrate the use of the following in your solution:
• Iteration (Looping)
• Modularity (using functions)
• Function Overloading (use overloaded functions for calculating Gross
Pay)
• Function Prototyping (create a function prototype for each of the
overloaded functions)
• Inter-function communication. To demonstrate inter-function
communication, all prompts for input must occur in the function
main(), all calculated gross pay amounts must be explicitly returned
to the function main(), and all output must be displayed by the
function main(). No output can be displayed by the functions.
• Use of pass-by-reference using Reference arguments. There must be,
at least, one example of pass-by-reference using Reference arguments
with each function in the program, except main(). Your program,
depending on the argument(s) supplied by the user, should invoke the
appropriate overloaded function.*
#include <iostream>
#include <iomanip>
using namespace std;
double grossPay(int number, double hours, double pay); // hourly function
double grossPay(int number, double salary); // salary function
double grossPay(int company, int project, int number, double hours, double pay); // contract function
double grossPay(int institution, int department, double hours, double pay); // intern function
int main() {
// prompt user for type of employee and give EOF instructions.
cout << "Enter '1' for hourly. Enter '2' for salaried." << endl;
cout << "Enter '3' for contracter. Enter '4' for intern." << endl;
cout << "If result is -1, the input was invalid, please input correct employee hours." << endl;
cout << endl;
cout << "Terminate input by using <ctrl> z on Windows then press enter." << endl;
cout << "Terminate input by using <ctrl> z on UNIX / Linux / Mac OS X then press enter." << endl;
int employeeType{ 0 };
int employeeNumber{ 0 };
double grossPay{ 0 };
double overtimePay{ 0 };
// salaried
double employeeSalary{ 0 };
// hourly
double hoursWorked{ 0 };
double payRate{ 0 };
// contractor
int companyNum{ 0 };
int projectNum{ 0 };
// intern
int schoolCode{ 0 };
int departmentCode{ 0 };
while (cin >> employeeType) {
switch (employeeType) {
case 1:
// HOURLY employee prompts and output
cout << "Enter employee number: " << endl;
cin >> employeeNumber;
cout << "Enter number of hours employee worked: " << endl;
cin >> hoursWorked;
cout << "Enter employees pay rate: " << endl;
cin >> payRate;
cout << setprecision(2) << fixed;
cout << "Gross pay of employee including overtime, is $" << grossPay(employeeNumber, hoursWorked, payRate) << endl;
cout << endl;
break;
case 2:
// SALARIED employee prompts and output
cout << "Enter employee number: " << endl;
cin >> employeeNumber;
cout << "Enter employees salary: " << endl;
cin >> payRate;
cout << setprecision(2) << fixed;
cout << "Gross pay of employee" << employeeNumber << "is $" << grossPay(employeeNumber, payRate) << endl;
cout << endl;
break;
case 3:
// CONTRACT employee prompts and output
cout << "Enter company number: " << endl;
cin >> companyNum;
cout << "Enter project number: " << endl;
cin >> projectNum;
cout << "Enter employee number: " << endl;
cin >> employeeNumber;
cout << "Enter number of hours employee worked: " << endl;
cin >> hoursWorked;
cout << "Enter employees pay rate: " << endl;
cin >> payRate;
cout << setprecision(2) << fixed;
cout << "Gross pay of contractor is $" << grossPay(companyNum, projectNum, employeeNumber, hoursWorked, payRate) << endl;
cout << endl;
break;
case 4:
// INTERN prompts and output
cout << "Enter institution code: " << endl;
cin >> schoolCode;
cout << "Enter department code: " << endl;
cin >> departmentCode;
cout << "Enter number of hours employee worked: " << endl;
cin >> hoursWorked;
cout << "Enter employees pay rate: " << endl;
cin >> payRate;
cout << setprecision(2) << fixed;
cout << "Gross pay of intern $" << grossPay(schoolCode, departmentCode, hoursWorked, payRate) << endl;
cout << endl;
break;
}
cout << "Enter '1' for hourly. Enter '2' for salaried." << endl;
cout << "Enter '3' for contracter. Enter '4' for intern." << endl;
cout << endl;
}
cout << endl;
cout << "Thank you for using this program. " << endl;
}
// hourly function
double grossPay(int number, double hours, double pay) {
double hourlyWeek{ 0 };
while (hours > 0 && hours <= 50.00) {
if (hours > 40.00) {
hourlyWeek = ((pay * 40.00) + (hours - 40.00) * (pay * 1.50));
}
else {
hourlyWeek = (hours * pay);
}
}
while (hours > 50.00) {
hourlyWeek = -1;
}
return hourlyWeek;
}
// salary function
double grossPay(int number, double salary) {
double salaryWeek{ 0 };
salaryWeek = (salary * 40);
return salaryWeek;
}
//contractor function
double grossPay(int company, int project, int number, double hours, double pay) {
double contractWeek{ 0 };
while (hours > 0 && hours <= 40.00) {
contractWeek = ((pay * 40.00) + (hours - 40.00) * (pay * 1.50));
}
while (hours > 40.00) {
contractWeek = -1;
}
return contractWeek;
}
// intern function
double grossPay(int institution, int department, double hours, double pay) {
double internWeek{ 0 };
while (hours > 0 && hours <= 20.00) {
if (hours > 15.00) {
internWeek = ((pay * 40.00) + (hours - 40.00) * (pay * 1.25));
}
else {
internWeek = (hours * pay);
}
}
while (hours > 20.00) {
internWeek = -1;
}
return internWeek;
}
rename your local variable:
double grossPay{ 0 };
because you cannot let your variables and function have the same name (grossPay)
by default, the compiler would use virable instead of the method, that's why you got the mistake :)
When it runs the winnings or losses are taken or added from the bank and then it is run again the bank is set back to a 25$ bank not the updated bank
int main()
{
srand(time(0));
int bank = 25;
int total;
char answer;
cout << "Come play Spin the Wheel. The wheel has numbers from 1-10." << endl
<< "If you spin an even number you lose that amount. If you spin" << endl
<< "an odd number you win that amount. You start with a 25$ bank." << endl;
cout << "Your bank is $" << bank << ". Would you like to spin the wheel? (y/n):" << endl;
cin >> answer;
while (toupper(answer) == 'Y')
{
int num = rand() % 10 + 1;
if (bank <= 10)
{
cout << "Sorry you must have more than 10$ to play" << endl;
}
else if (num % 2 == 0 )
{
total = bank + num;
cout << "You spun a " << num << " and won $" << num << endl;
cout << "Your bank is now: $" << total << endl;
}
else
{
total = bank - num;
cout << "You spun a " << num << " and lost $" << num << endl;
cout << "Your bank is now: $" << total << endl;
}
cout << "Would you like to play Again (y/n) ?" << endl;
cin >> answer;
}
return 0;
}
When it runs the winnings or losses are taken or added from the bank and then it is run again the bank is set back to a 25$ bank not the updated bank
You initialize bank to be 25 dollar in this function. Inside the while loop only total is updated not bank.
Another problem arises when there is too few money to play. I suppose you would like to display your message one time, but you are stuck inside the loop because it is never broken out of.
I believe your else if and else statements are backwards.
num % 2 == 0
Would signify that the number was even, if true. The instructions say that you lose the money if the number is even.
Bank will never be less than or equal to 10 because you are never setting bank to anything after the initial 25. Its always 25.
The variable total seems redundant. Maybe add or subtract the amount rolled directly from bank.
You need to set
bank = total
else you never change its value
So I am a bit rusty in my programming skills and don't have any real world experience except for the college classes I have taken in the past. I am working on a program for a class but running into a snag;I cannot figure out how to use the value of a variable inside a For loop outside of the loop. Here is the code I am referencing:
#include "iostream"
using namespace std;
int want, have, need;
int counter = 0;
char response, cont;
int diff(int want, int have);
int main(){
cout << "Welcome!\n";
cout << "This program will help you reach your money saving goals!\n";
cout << "Would you like to use this program? (y/n)\n";
cin >> response;
while (response == 'y'){
cout << "Please enter all amounts in whole dollars only!\n";
cout << "Please enter the amount of money you would like to have saved: $";
cin >> want;
cout << "\nPlease enter the amount of money you currently have saved: $";
cin >> have;
if (have >= want){
cout << "You have already reached or exceeded your goal, this program will not be able to help you!\n";
system("Pause");
return 0;
}
cout << "\nYou need to save $" << diff(want, have) << " more money to reach your goal!\n";
cout << "Would you like me to help you with a savings plan?";
cin >> cont;
while (cont == 'y'){
int menu;
cout << "Please select from the following options: \n";
cout << "1 - Daily Saving Plan\n";
cout << "2 - Weekly Saving Plan\n";
cout << "3 - Monthly Saving Plan\n";
cout << "Enter the number associated with your choice: \n";
cin >> menu;
switch (menu){
case 1: {
int daily;
cout << "You have chosen the Daily Savings Plan\n";
cout << "How much money can you save every day? $";
cin >> daily;
for (int x = daily; x < need; x++){
daily = daily + daily;
counter++;
}
cout << "\nIt will take you " << counter << " days to reach your goal!\n";
break;
}
case 2: {
int weekly;
cout << "You have chosen the Weekly Savings Plan\n";
cout << "How much money can you save every week? $";
cin >> weekly;
for (int x = weekly; x < need; x++){
counter++;
}
cout << "\nIt will take you " << counter << " weeks to meet your goal!\n";
break;
}
case 3: {
int monthly;
cout << "You have chosen the Monthly Savings Plan\n";
cout << "How much money can you save every month? $";
cin >> monthly;
for (int x = monthly; x < need; x++){
monthly = monthly + monthly;
counter++;
}
cout << "\nIt will take you " << counter << " months to reach your goal!\n";
break;
}
default: cout << "You made an invalid selection";
cout << "Would you like to look at a different saving plan? (y/n)\n";
cin >> cont;
}
}
}
}
int diff(int want, int have){
return want - have;
}
So, when I run the program, everything runs ok, but the value of counter is always shown as "0" in the final cout statement.
I understand why it is doing this, I think..and it's because of the "int counter = 0" declaration outside the loop, so I assume it goes back to that value after the loop exits.
If I do not initiate the counter variable, I get an error, and if I declare the value inside the loop, I get an error trying to use it in the cout statement as I have above.
I'm not even sure my for loop is structured correctly...basically I want it to add to itself the weekly variable, until the total of x = need. I also want to capture how many iterations it takes for that, then output it as the number of weeks. Hopefully that all makes sense; any and all help is appreciated.
It seems like what you want to do can be done with ceil(double(need/weekly)) and that rounds up need divided by weekly.
Your declaration outside the loop doesn't affect the value you cout after you finished the for loop.
As for your problem, it looks like you never initialized need so your for loops never made an iteration as undefined is not less than or equal to 0.
A sketch in C++11 of your program.
char prompt( std::initializer_list<const char*> message, std::initializer_list<const char*> question, std::initializer_list<char> options ) {
for( auto msg:message )
std::cout << msg;
while(true) {
char response;
for( auto q:question)
std::cout << q;
std::cin >> response;
for (char option:options) {
if (response == option)
return response;
}
}
}
int prompt( std::initializer_list<const char*> message, std::initializer_list<const char*> question, int min = 0, int max = std::numeric_limits<int>::max() ) {
for( auto msg:message )
std::cout << msg;
while(true) {
int response;
for( auto q:question)
std::cout << q;
std::cin >> response;
if (response >= min && response <= max)
return response;
}
}
}
void saving( const char* plan, const char* unit, const char* units, int target ) {
int daily = prompt(
{"You have chosen the ", plan, "\n"},
{"How much money can you save every ", unit, "? $"},
1 // min saving of 1$ per unit time to prevent infinite loops
);
std::cout << "\n";
int counter = 0;
int amount_saved = 0;
while (amount_saved < target) {
++counter;
amount_saved += daily;
}
if (counter != 1)
std::cout << "It will take you " << counter << " " << units << " to reach your goal\n";
else
std::cout << "It will take you " << counter << " " << unit << " to reach your goal\n";
}
int main() {
while(
prompt(
{"Welcome!\nThis program will help you reach your money saving goals!\n"},
{"Would you like to use this program? (y/n)\n"},
{'y', 'n'}
) == 'y'
)
{
int want = prompt( {"Please enter all amounts in whole dollars only!\n"},
{"Please enter the amount of money you would like to have saved?"} );
int have = prompt( {"\n"}, {"Please enter the amount of money you currently have saved?\n"} );
std::cout << "\n";
if (have >= want) {
std::cout << "You win!\n";
system("Pause"); // ick
return 0;
}
std::cout << "You need to save $" << (have-want) << " more money to reach your goal!\n";
while( 'y' == prompt(
{},
{"Would you like me to help you with a savings plan? (y/n)"},
{ 'y', 'n' }
)) {
char menu = prompt(
{
"Please select from the following options: \n",
"1 - Daily Saving Plan\n",
"2 - Weekly Saving Plan\n",
"3 - Monthly Saving Plan\n"
},
{"Enter the number associated with your choice: \n"},
{ '1', '2', '3' }
);
switch (menu) {
case '1': {
saving( "Daily Saving Plan", "day", "days", have-want);
} break;
case '2: {
saving( "Weekly Saving Plan", "week", "weeks", have-want);
} break;
case '3': {
saving( "Monthly Saving Plan", "month", "months", have-want);
} break;
}
}
}
}
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 ;)