I am learning C++ as part of my course at Uni. I am not all that experienced in c++ but I have searched for possible solutions for several hours and tested hundreds of variations of code and I still cannot get this working. I believe that my use of Enums must be fundamentally wrong - I have never got them working as I intended. For this task we had to use Enums and a switch statement.
#include <iostream>
using namespace std;
enum roomType { Deluxe = 250, Twin = 150, Single = 110};
int temp;
int total;
int input = 1; int yes = 1; int no = 0;
void GetInput()
{
cin >> input;
temp = temp*input;
}
int main()
{
if (input != 0)
{
cout << "\nRoom Price Code\n------------------------------------\nDeluxe Room " << "\x9C" << "200 D\nTwin Room " << "\x9C" << "150 T\nSingle " << "\x9C" << "110 S\n\n";
cout << "Enter room type:";
GetInput();
switch (input) {
case Deluxe:
temp = Deluxe;
break;
case Twin:
temp = Twin;
break;
case Single:
temp = Single;
break;
default:
//prevents infinite loop bug
system("pause");
cout << "Entry not recognized";
main();
break;
}
cout << "\nEnter number of rooms:";
GetInput();
cout << "\nEnter number of nights:";
GetInput();
total = total + temp;
cout << "\n\x9C" << total << "\n";
cout << "More rooms? yes/no: ";
cin >> input;
main();
}
cout << "Discount? yes/no: ";
GetInput();
if (input = 1)
{
total = ((total / 100) * 75);
cout << "\n\x9C" << total << "\n";
}
cout << "your total is "<<"\x9C" << total;
system("pause");
system("cls");
return 0;
}
If the User enters a room type for instance Deluxe, the case statement always goes to default, then without the system("pause"); would proceed to get stuck in a loop.
For some reason the program seems to ignore all the cin >> input;'s after the first one. I know that it is this that is causing the looping. I have tried switching cin>> out for a getline(cin,input)alternative but that doesn't seem to work either.
Just compiled your code. You are not doing anything wrong for Delux. Just silly error that enum value is 250 and you are displaying 200. So while running, you are entering 200 and it goes to default.
Coming to second question that why program runs only once, its because you want it that way. The check if (input != 0) checks for input type as integer value. You might be entering 'yes' in command line and not doing any error checks. Try entering integer value.
PS: In future, please paste the code in question itself.
NOTE: This does not answer the users question directly; I have done that above. This is an example that is based off of one of the replies from the user and is here to demonstrate the uses of enumerations and enumerated types so that they may be able to have an easier and better understanding of them.
Here are two function prototypes that would do the same thing one uses enumerations while the other doesn't.
enum ProductType {
HARDWARE = 1,
TOOLS,
APPLIANCES,
FURNITURE,
LAWN_AND_GARDEN,
PAINT
};
// This Version Doesn't Use An Enumerated Value And Takes In An Unsigned Int
float calculateProductTotalCost( unsigned int productType, float costOfProduct, unsigned int numberOfItems );
float calculateProductTotalCost( ProductType type, float costOfProduct, unsigned int numberOfItems );
someOtherFunction() { // Could be main()
// This function has a magic number to represent the product type
calcluateProductTotalCost( 3, 1499.99f, 2 );
// This version uses the enumeration with the scope resolution operator
// to allow the calling of this function to be easier to read.
calculateProductTotalCost( ProductType::PAINT, 23.50f, 150 );
// Although I did not show any implementation for these functions
// since that is irrelevant, the importance of the two is that in
// practice these methods would be the same and perform the same
// exact calculation and operation. It is just more readable for
// another human to see your code when they have to work on it
// sometime in the future and you are not there to explain what you
// did and why you did it. It can even be a help for yourself if
// you go back to code that you have written that you have not seen
// in a few months or years. Then just by reading the Wording
// of the Enumeration you know that this value represents this specific
// object.
}
Here is another example
SoundSource {
CLAP = 1,
BANG,
GUN_SHOT,
THUNDER_BOLT,
LAUGHTER,
SCREAM,
};
bool playSound( unsigned int, bool bLoop );
bool playSound( SoundSource, bool bLoop );
someFunction() {
// Which group of function calls looks better and is easier to understand; Group A or Group B?
// Group A
playSound( 6, false );
playSound( 4, true );
playSound( 3, false );
// Group B
playSound( SoundSource::THUNDER_BOLT, true );
playSound( SoundSource::SCREAM, false );
playSound( SoundSource::LAUGH, true );
}
I hope this helps you to understand the uses of Enums; they are great for a few different things, good for switch case statements, and for allowing different data types that are usually passed in by an ID value usually an unsigned to also be represented by words that are an enumerated value. If you notice it is good practice to name all of your Values within the Enum in ALL_CAPS separating each word by an underscore; but this is also just preference, but most people will recognize this as an enum when they see all caps.
You have a lot of errors in this code; I structured the enum to represent an enumerated value for a switch selection, the prices are assigned in the case statements. Many times are you making a call to main(); I've never seen this done in practice! I can not say that it is invalid or illegal, but I've never seen it! I chose appropriate variable types for the right kind of concept or idea such as the cost of something being a float, when you ask user for input if there are more rooms or not or if there is a discount or not I used a bool type. Values that you know that will not be negative I used unsigned. I removed all global variables (usually bad practice). I fixed some formatting for easier readability.
Here is what I did and I have some comments to explain the changes I've made; other changes you will need to think about what I have done.
#include <iostream>
// using namespace std; // Bad Practice
enum RoomType {
NONE = 0, // NONE For Default Value - No Room Type Selected
DELUXE,
TWIN,
SINGLE,
LAST // MUST BE LAST!
};
/*void GetInput() { // Function Not Really Required In This Simple Application
cin >> input;
temp = temp*input;
}*/
int main() {
while ( true ) {
float totalCost = 0; // Renamed Variable For Better Readability
int input = 0; // Initialized To 0, We Do Not Know What The User Will Choice
std::cout << std::endl << "Room Price Code" << std::endl
<< "------------------------------------" << std::endl
<< "Deluxe Room " << "\x9C" << "250 D" << std::endl
<< "Twin Room " << "\x9C" << "150 T" << std::endl
<< "Single " << "\x9C" << "110 S" << std::endl << std::endl;
std::cout << "Please Make A Selection:" << std::endl
<< "1 - Deluxe" << std::endl
<< "2 - Twin" << std::endl
<< "3 - Single" << std::endl << std::endl;
std::cin >> input;
// You Never Declare Variable Type Of RoomType
RoomType type = static_cast<RoomType>( input ); // Cast input to RoomType
float costOfRoom = 0.0f;
switch (type) {
case NONE: {
costOfRoom = 0.0f;
break;
}
case DELUXE: {
costOfRoom = 250.0f;
break;
}
case TWIN: {
costOfRoom = 150.0f;
break;
}
case SINGLE: {
costOfRoom = 110.0f;
break;
}
default: {
std::cout << "Entry not recognized";
//main(); wrong
break;
}
} // Switch
unsigned numRooms = 0;
unsigned numNights = 0;
std::cout << std::endl << "Enter number of rooms:";
std::cin >> numRooms;
std::cout << std::endl << "Enter number of nights:";
std::cin >> numNights;
totalCost = costOfRoom * numNights * numRooms;
std::cout << "\n\x9C" << totalCost << "\n";
bool moreRooms = false;
bool hasDiscount = false;
input = 0;
std::cout << "More rooms? 1 for yes - 0 for no: ";
std::cin >> moreRooms;
if ( moreRooms ) {
std::cout << "Please Enter Number Of Rooms. ";
std::cin >> input;
totalCost += (costOfRoom * numNights * input);
}
// main(); // Wrong!
std::cout << "Discount? 1 for yes - 0 for no: ";
std::cin >> hasDiscount;
if ( hasDiscount ) {
totalCost = ((totalCost / 100) * 75);
std::cout << std::endl << "\x9C" << totalCost << std::endl;
}
std::cout << "Your total is " <<"\x9C" << totalCost << std::endl;
bool runAgain = false;
std::cout << std::endl << "Would you like to contine? 1 - yes - 0 for no:";
std::cin >> runAgain;
if ( !runAgain ) {
break;
}
} // while
system("pause");
system("cls");
return 0;
} // main
Related
I need help. I'm currently learning C++ programming and I'm still at the beginner level. I'm still figuring out how to make the while loop working. My idea is when inserting the correct code input, the switch statement choose the right case statement and loop back to insert another input until 0 inserted to stop the loop and calculate for the final output in main() constructor.
I know I have few kinks to fix soon but I'm still struggling to figure out this particular part.
#include <stdio.h>
#include <iostream>
#include <iomanip>
using namespace std;
double sst = 0.06, total = 0, grandTotal, price, discount, newPrice, totalSST;
int quantity, count, code;
string name, ech;
void item001(){
name = "Rice (5kg)";
price = 11.5;
discount = 0;
}
void item002(){
name = "Rice (10kg)";
price = 25.9;
discount = 0;
}
void item003(){
name = "Sugar (1kg)";
price = 2.95;
discount = 0;
}
void item_cal(){
cout << "Please enter the quantity of the item: ";
cin >> quantity;
newPrice = (price + (discount * price)) * quantity;
cout << "\nItem: " << name << " || Quantity: " << quantity << " || Price: RM" << newPrice << endl;
}
void input(){
cout << "Welcome SA Mart\n" << "Please insert the code. Press 0 to stop: ";
while (code != 0){
cin >> code;
switch (code){
case 001:
item001();
item_cal();
break;
case 002:
item002();
item_cal();
break;
case 003:
item003();
item_cal();
break;
default:
cout << "\nWrong code" << endl;;
break;
total += newPrice;
}
}
}
int main(){
input();
totalSST = total * sst;
grandTotal = total + totalSST;
cout << fixed << setprecision(2);
cout << "Total: RM" << total << " ||SST: RM" << totalSST << " || Grand Total: RM" << grandTotal << endl;
return 0;
}
The only functional issue I see in your code is that there is a chance that the code variable will initialize to 0 (depends on the compiler/randomness). If that happens, your input method will return before it enters the loop. Other than that it looks like it will work. Of course, programming is not just the art of "making it work," style and readability are important too. In general, you want to confine variables to the smallest scope in which they are referenced. 'code' should not be a global variable, it should live in the input method. As for the loop, there are several ways it could be implemented: a "while(true)" loop could be used, in which case the variable may be defined inside the loop; on the other hand a "do while" would guarantee one loop runs (perhaps that would be a good fit here), but the variable must live outside of the loop, at least int the scope of conditional check. The way you choose is often a matter of style. Below, I use a "while(true)."
In programming, readability matters (a lot). I think this program would be easier to read if the data were broken up into a few structs, perhaps "Bill," and "Food." Another thing to consider is how to broaden the usage of your program, without introducing significant complexity. For example, it could work for any grocery store (any set of food items/prices). This is often a matter of determining an appropriate set of parameters to feed your program.
To do these things you might write something like this:
#pragma once
#include <string>
#include <map>
using namespace std;
namespace market {
const double& sst = 0.06;
struct Bill {
double total = 0;
double totalSST = 0;
double grandTotal = 0;
};
struct Food {
const char* name;
double price;
double discount;
Food(const char* name, double price, double discount = 0)
: name(name), price(price), discount(discount) {}
double result_price() const {
return price - price * discount;
}
};
struct GroceryStore {
const char* name;
std::map<int, Food> inventory;
GroceryStore(const char* name, std::map<int, Food> inventory)
: name(name), inventory(inventory) { }
};
void shop(const GroceryStore& store, Bill& bill, bool show_menu = false, int exit_code = 0) {
// check error conditions
if (store.inventory.find(exit_code) != store.inventory.end()) {
// that's the 'exit_code' code silly!
cout << "Bad store. Come back another time." << endl;
return;
}
cout << "Welcome to " << store.name << endl;
if (show_menu) {
cout << "The following items are available for purchase:" << endl;
for (auto p : store.inventory) {
cout << "\t" << p.first << ") " << p.second.name << "(" << p.second.result_price() << endl;
}
}
cout << "Enter the product code of the item you wish to purchase:";
int code;
cin >> code;
while (true) {
auto food_it = store.inventory.find(code);
if (food_it == store.inventory.end()) {
cout << "Thanks for stopping by." << endl;;
break;
}
cout << "Please enter the quantity of the item: ";
uint32_t quantity;
cin >> quantity;
auto& food = food_it->second;
auto disc_price = food.price - (food.discount * food.price);
bill.total += disc_price * quantity;
cout << "\nItem: " << food.name << " || Quantity: " << quantity << " || Price: RM" << disc_price << endl;
cout << "Would you like anything else? Enter the product code, or press " << exit_code << " to proceed to check-out." << endl;
cin >> code;
}
}
void ring_up(Bill& bill) {
bill.totalSST = bill.total * sst;
bill.grandTotal = bill.total + bill.totalSST;
}
void run() {
int code = 1;
GroceryStore store("SMart", {
{ code++, Food("Rice (5kg)", 11.5, 0) },
{ code++, Food("Rice (10kg)", 25.9) },
{ code, Food("Sugar (1kg)", 2.95, 0) }
});
Bill bill;
shop(store, bill, true);
ring_up(bill);
cout << "Total: RM" << bill.total << " ||SST: RM" << bill.totalSST << " || Grand Total: RM" << bill.grandTotal << endl;
}
}
Firstly there is a bug in input when u will input 0 then also it won't break while loop as code that is checked contains the previous value.
for example:
input is
3
0
but according to your code when the code will run the second time and while condition is checked code still contains 3 as value and code will run one more time
Try initialising code to some value, for example, -1. I'm not really sure but I think for global int variables, they initialise int variables to 0. So your first loop doesn't run. Or another way to do it is using do while loops instead of while loop.
do {
cin >> code;
switch (code){
case 001:
item001();
item_cal();
break;
case 002:
item002();
item_cal();
break;
case 003:
item003();
item_cal();
break;
default:
cout << "\nWrong code" << endl;;
break;
total += newPrice;
} while (code != 0);
}
This makes sure that the loop will run at least once, making code initialised.
Hope it helps you! Have fun programming!
#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
int numofEmployees();
int daysMissed(int);
int AverageMissed(int, int);
int main()
{
cout << "Welcome to employee absentee calculator!" << endl;
int numEmployees = numofEmployees();
int Missed = daysMissed(numEmployees);
double misAverage = AverageMissed(numEmployees, Missed);
cout << "There are " << numEmployees << " in the company. They have missed " << Missed << " days total. On average, they have missed " << misAverage << " days." << endl;
return 0;
}
int numofEmployees() {
cout << "How many employees are in your company? ";
int employees;
cin >> employees;
while (employees < 1) {
cout << "Employee count must 1 or greater!" << endl;
}
return employees;
}
int daysMissed(int numEmployees) {
int Absence, totAbsence = 0;
for (int i = numEmployees; i < numEmployees; i++) {
cout << "How many days has each employee missed this passed year? ";
cin >> Absence;
totAbsence += Absence;
}
while (Absence < 0) {
cout << "Values entered must be positive numbers!" << endl;
cin >> Absence;
}
return totAbsence;
}
int AverageMissed(int numEmployees, int Missed){
double Average;
Average = double(numEmployees) / double(Missed);
return Average;
}
This code is being used to calculate the average number of employee absences by way of using three functions. The second function is not working correctly as it is not being called properly by the main. This is for a school assignment.
The problem is daysMissed - if numEmployees is <= 0, then Absense will be uninitialized. But, you say, "I check that in numofEmployees" - the problem is that the compiler doesn't do that sort of whole-program analysis before issuing these warnings.
There is another problem: daysMissed is wrong (twice). If there are two employees, and I enter -2 and 1, there will be no error for the negative number. If on the other hand, if I enter 1 and -2, you never correct totAbsence. You would be much better off writing a little function which reads a number >= some limit in a loop, and keeps prompting until given the correct value. Something like:
int read(const char* prompt, const char* err_prompt, int limit) {
cout << prompt << endl;
for(;;) {
int result;
cin >> result;
if (result >= limit) {
return result;
}
cout << err_prompt << endl;
}
}
Then daysMissed becomes much pleasanter to write - and you can use the same function to read the number of employees (which will go into an infinite loop at the moment)
You should also validate a division by zero plus change the return type.
double AverageMissed(int numEmployees, int Missed){
if (Missed > 0) return double(numEmployees) / Missed;
return 0;
}
by the way, there is no need to cast both operands in the division (/). Casting one of them will be enough to return a double type.
Below you will find my dismal attempt to create a user defined function. I am trying to do an assignment that calculates the area and cost of installing carpet for various shapes. I am also suppose to keep a running total of them. In addition the assignment requires that I use a used defined function. Right now all it does is accept the input of 1 and ask "What is the length of the side: ". It then loops back to the selection menu. It does not calculate a total much less keep track of the total. What am I doing wrong in creating the user defined function and how can I incorporate it to keep a running total till they exit?
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cmath>
using namespace std;
void square(double);
const double UNIT_PRICE = 2.59;
const double LABOR_COST = 32.5;
const double PIE = 3.14;
const double TAX = .0825;
int main() {
int selection;
int sqrSide = 0;
// declare and initialize the variables for the shape
int sqrTot = 0;
do {
// get input from user as to what they want to do
cout << "Carpet Area Shape" << endl;
cout << "1. Square" << endl;
cout << "2. Rectangle" << endl;
cout << "3. Circle" << endl;
cout << "4. Triangle" << endl;
cout << "5. Done" << endl;
cout << "Type a number to continue: ";
cin >> selection;
cout << endl;
// loop through the solutions based on the user's selection
switch (selection) {
case 1:
cout << "What is the length of the side: ";
cin >> sqrSide;
square(sqrSide);
if (sqrTot > 0) {
cout << "Shape: Square" << endl;
cout << "Side: " << sqrSide << endl;
cout << "Area: " << sqrTot << endl;
}
cout << endl;
system("pause");
break;
case 2:
case 3:
case 4:
case 5: // exit
system("cls");
break;
default:
"You have made an invalid selection. Please choose a number from the "
"list.";
cout << endl;
}
// loop through if the user is still making a valid selection
} while (selection != 5);
system("pause");
return 0;
}
void square(double) {
double sqrSide = 0;
double sqrTot = 0;
double sqrArea;
sqrArea = sqrSide * 4;
// get the total area and store it as a variable
sqrTot += sqrArea;
if (sqrTot > 0) {
cout << "Shape: Square" << endl;
cout << "Side: " << sqrSide << endl;
cout << "Area: " << sqrTot << endl;
}
}
When you declare the prototype of the function you can omit the parameter but in the implementation you must place it.
change:
void square(double)
{
double sqrSide = 0;
double sqrTot = 0;
double sqrArea;
sqrArea = sqrSide * 4;
//get the total area and store it as a variable
sqrTot += sqrArea;
if (sqrTot > 0) {
cout << "Shape: Square" << endl;
cout << "Side: " << sqrSide << endl;
cout << "Area: " << sqrTot << endl;
}
}
to:
void square(double sqrSide)
{
double sqrTot = 0;
double sqrArea;
sqrArea = sqrSide * 4;
//get the total area and store it as a variable
sqrTot += sqrArea;
if (sqrTot > 0) {
cout << "Shape: Square" << endl;
cout << "Side: " << sqrSide << endl;
cout << "Area: " << sqrTot << endl;
}
}
and also change:
case 1:
cout << "What is the length of the side: ";
cin >> sqrSide;
square(sqrSide);
if (sqrTot > 0) {
cout << "Shape: Square" << endl;
cout << "Side: " << sqrSide << endl;
cout << "Area: " << sqrTot << endl;
}
cout << endl;
system("pause");
break;
to:
case 1:
cout << "What is the length of the side: ";
cin >> sqrSide;
square(sqrSide);
system("pause");
break;
As mentioned by πάνταῥεῖ in a comment, it seems that you've a few misconceptions regarding scope of variables, about parameters and about return values. Let's see if we can't dispel some of those.
First of all, lets talk about scope. When we declare a variable inside a block delimited with { and }, the variable only exists inside that block. Code that follows the block cannot access the variable.
So, this is okay:
int a = 3;
int b = 2;
int c = a*b;
But, this is not, since the values of a and b are no longer available:
{
int a = 3;
int b = 2;
}
int c = a*b;
Next, lets talk about parameters. These are the inputs to functions which the function will use in order to complete its task. While their name is irrelevant and essentially meaningless, it will certainly help you and others of you give them meaningful names. Some programming languages and indeed, students of some disciplines don't follow this maxim and can produce code that's harder to follow than it need be. The implementation of Basic found in 20 year old Texas Instruments calculators and physicists, I'm looking at you!
Consider the following functions, (whose bodies I've ommitted for brevity):
double calcArea(double a)
{
...
}
double calcArea(double b)
{
...
}
They both suck. What's a stand for, how about b?
A far better pair might resemble:
double calcArea(double radius)
{
...
}
double calcArea(double sideLenOfSquare)
{
...
}
Lastly, lets talk about return values. In each of the 4 preceding functions, the declaration begins with double. This means that we can expect to get back a value of type double from the function. However, this is just coding - there's no magic and as such, we need to actually let the compiler know what this value will be. Extending the two previous functions, we might come up with some something like the following:
double calcArea(double radius)
{
return 3.1415926535 * (radius * radius);
}
double calcArea(double sideLenOfSquare)
{
return sideLenOfSquare * sideLenOfSquare;
}
Now as it turns out - even these two simple functions are not all they've cracked-up to be. Namely, the first function uses a constant - π (Pi or 3.141....) This already exists (and with far better precision than I've used) in the math.h header file. If this file is included, we then have access to the #defined constant, M_PI.
Next, both of these functions have the same name and take the same number of parameters of identical type. The compiler can't possibly know which one you'd like to invoke. At a minimum, they should have different names. Perhaps something like calcCircleArea and calcSquareArea. Now, the compiler knows which function you're referring to and will happily compile this part of the code. Errors may exist elsewhere, but these are a different matter.
A little research on function overloading will provide resources that can explain the problem and solution to functions with the same name far better than I am both able and inclined to try. :)
Been working on this program for a while now. (had some problems and asked a few times here.) Ran into another one though! The program asks for my account type twice. Can not figure out why or how to fix it. Any help is appreciated, thanks!
/*
project3.cpp
Andre Fecteau
CSC135-101
October 29, 2013
This program prints a bank's service fees per month depending on account type
*/
#include <iostream>
using namespace std;
/*
Basic Function for Copy Paste
<function type> <function name> (){
// Declarations
// Initalizations
// Input
// Process
// Output
// Prolouge
}
*/
void displayInstructions (){
// Declarations
// Initalizations
// Input
// Process
// Output
cout <<"| -------------------------------------------------------------- |" << endl;
cout <<"| ---------- Welcome to the bank fee calculator ---------------- |" << endl;
cout <<"| -------------------------------------------------------------- |" << endl;
cout <<"| This Program wil ask you to eneter your account number. |" << endl;
cout <<"| Then it will ask for your account type Personal or Commercial. |" << endl;
cout <<"| Then ask for the amount of checks you have written. |" << endl;
cout <<"| Lastly it will output how much your fees are for this month. |" << endl;
cout <<"| -------------------------------------------------------------- |" << endl;
cout << endl;
// Prolouge
}
int readAccNumb(){
// delarations
int accNumber;
// intitalizations
accNumber = 0.0;
// input
cout << "Please Enter Account Number:";
cin >> accNumber;
// Procesas
// output
// prolouge
return accNumber;
}
int checksWritten (){
// Declarations
int written;
// Initalizations
written = 0.0;
// Input
cout <<"Please input the amount of checks you have written this month:";
cin >> written;
// Output
// Prolouge
return written;
}
char accType (){
// Declarations
char answer;
int numberBySwitch;
// Initalizations
numberBySwitch = 1;
// Input
while (numberBySwitch == 1){
cout << "Please Enter the acount type (C for Comerical and P for Personal):";
cin >> answer;
// Process
switch (answer){
case 'p':
answer = 'P';
numberBySwitch += 2;break;
case 'P':
numberBySwitch += 2;break;
case 'c':
answer = 'C';
numberBySwitch += 3;break;
case 'C':
numberBySwitch += 3;break;
default:
if(numberBySwitch == 1) {
cout << "Error! Please enter a correct type!" <<endl;
}
}
}
// Output
// Prolouge
return answer;
}
int commericalCalc(int checksWritten){
// Declarations
int written;
int checkPrice;
// Initalizations
checkPrice = 0.0;
// Input
// Process
if(written < 20){
checkPrice = 0.10;
}
// Output
// Prolouge
return checkPrice;
}
int personalCalc(int checksWritten){
}
double pricePerCheck(char accType, int checksWritten){
// Declarations
double price;
char answer;
// Initalizations
price = 0.0;
// Input
// Process
if(accType == 'P'){
}
if(accType == 'C'){
if(checksWritten < 20){
price = 0.10;
}
}
// Output
// Prolouge
return price;
}
int main(){
// Declarations
int accountNumb;
char theirAccType;
int writtenChecks;
double split;
// Initalizations
accountNumb = 0.0;
writtenChecks = 0.0;
split = 0.0;
theirAccType = ' ';
// Input
displayInstructions();
theirAccType = accType();
accountNumb = readAccNumb();
split = pricePerCheck(accType(), checksWritten());
// Output
cout << endl;
cout << "Account Type: " << theirAccType << endl;
cout << "Check Price: " << split << endl;
// Prolouge
return 0;
}
theirAccType = accType();
...
split = pricePerCheck(accType(), checksWritten());
// ^^^^^^^^^
You're calling accType for the second time. You should be passing in the variable that you used to hold the initial call on the first line.
split = pricePerCheck(theirAccType, checksWritten());
// ^^^^^^^^^^^^
The request for account type is made in the accType() function. You're calling that function twice in this code:
displayInstructions();
theirAccType = accType();
accountNumb = readAccNumb();
split = pricePerCheck(accType(), checksWritten());
accType() is called to assign the value to theirAccType, and again as an argument to pricePerCheck().
You probably need
split = pricePerCheck(theirAccType, checksWritten());
When you call pricePerCheck() you pass the result of calling accType() rather than theirAccType: you stored the result of the first call but you are making a second call. C++ doesn't memoize the result of function calls.
BTW, you want to compile your code with a higher warning level! There are number of fatal issues in your code:
personalCalc() is declared to return an int but doesn't return anything (the function isn't call, though, i.e. your question, obviously, isn't a SSCCE.
The function commericalCalc() uses the the value of an uninitialized variable (written). It seems to be also badly named.
/*I got stumped within my code. I think classes will be simpler than structures, but the chapter within my book makes me do structures. : / I am currently getting an error message that my function was not matched up for an overloaded function. The book does talk about them, but the examples of overloading functions in the book aren't helping me out. Also the book wants me to enter account numbers and fill in the objects and when they are asked for an account number they should have the opportunity to "QUIT" entering numbers and proceed onto the next part of the program; that whole way of thinking has my brain a bit fried and I was hoping I could get some help. I apologize if the formatting of my code is messy, I tried to reformat it within here so it would all go into the code brackets.
The Error happens at line... 161 at the displayAccounts function. Parameters were different within the top and bottom of the two functions I changed it and it works. I am going to go over different parts and if its correct post the correct code.*/
I figured out exactly the question that I need. I need the "QUIT" loop to be allowed to be followed up within the account numbers. This would allow the user to enter in a 0 at any time when asked to enter an account number and this was what was confusing me the most.
#include <iostream>
#include <iomanip>
using namespace std;
struct BankAccount
{
void enterAccountsData(BankAccount *accounts);
void computeInterest(BankAccount *accounts);
void displayAccounts(BankAccount *accounts, const int QUIT);
int accountNum; // holds the account number.
double accountBal; // holds the account balance.
double annualInterest; // holds the interest rate.
int term; // holds the term for the accounts.
};
int main()
{
const int MAX_ACCOUNTS = 100; // The maximum number of bank accounts.
const int QUIT = 0; // sentinal value.
int input;
int num = 0;
BankAccount data[MAX_ACCOUNTS];
BankAccount display;
cout << "Enter " << QUIT << " to stop, otherwise enter 1 and procreed.";
cin >> input;
while(true)
{
if(input != QUIT)
{
data[MAX_ACCOUNTS].enterAccountsData(data);
data[MAX_ACCOUNTS].computeInterest(data);
}
else
{
break;
}
}
display.displayAccounts(data, QUIT);
//system("pause");
return 0;
}
void BankAccount::enterAccountsData(BankAccount *accounts)
{
cout << setprecision(2) << fixed;
const int NUM_OF_ACCOUNTS = 100; // the number of bank accounts. (change the number for more bank accounts)
int found;
int quit = 0;
/* First for loop which asks and holds the account information
entered in by the user. */
for(int num = 0; num < NUM_OF_ACCOUNTS; num++)
{
do
{
found = 0;
cout << "Enter in account # " << (num + 1) << endl;
cin >> accounts[num].accountNum; // holds the value of the account number
// Checks if the account number is valid.
while(accounts[num].accountNum < 999 || accounts[num].accountNum > 10000)
{
cout << "Account number must be four didgets:" << endl;
cin >> accounts[num].accountNum;
}
// Checks if the account numbers are the same.
for(int check = 0; check < num; check++)
{
while(accounts[num].accountNum == accounts[check].accountNum)
{
cout << endl << "Account Numbers cannot be the same, enter in a new account number." << endl;
found = 1;
break;
}
}
} while(found); // end of do while.
// Holds the values for the account balances.
cout << "Enter the accounts balance." << endl;
cin >> accounts[num].accountBal;
// Makes sure that the account balance is not negative.
while(accounts[num].accountBal < 0)
{
cout << "Account cannot have a negitive balance." << endl;
cin >> accounts[num].accountBal;
}
// Holds the interest rate.
cout << endl << "Enter the interest rate for account # " << (num + 1) << endl;
cin >> accounts[num].annualInterest;
// Makes sure the interest rate is valid
while(accounts[num].annualInterest > 0 && accounts[num].annualInterest > 0.15)
{
cout << endl << "Annual interest must be from 0 to 0.15." << endl;
cin >> accounts[num].annualInterest;
}
// Makes sure the interest rate is not negetive
while(accounts[num].annualInterest < 0)
{
cout << endl << "Interest rate cannot be negetive" << endl;
cin >> accounts[num].annualInterest;
}
// Holds the value for the length of the interest.
cout << endl << "How many years will this interest rate be held for? " << endl;
cin >> accounts[num].term;
//Checks for valid length of time for the term held
while(accounts[num].term < 0 || accounts[num].term > 11)
{
cout << "The Term must be greater than 1 and should not exceed 10" << endl;
cin >> accounts[num].term;
}
}
cout << "If you wish to stop enter 0 otherwise type 1 to proceed" << endl;
cin >> quit;
if(quit = 0)
{
return;
}
}
void BankAccount :: computeInterest(BankAccount *accounts)
{
const int NUM_OF_ACCOUNTS = 100; // the number of bank accounts.
const int MONTHS_IN_YEAR = 12;
double total = 0;
double average = 0;
for(int num = 0; num < NUM_OF_ACCOUNTS; num++)
{
/*Goes through the term year and calculates the total
of each account balance. Then calculates the average. */
for(int year = 0; year < accounts[num].term; year++)
{
for(int month = 0; month < MONTHS_IN_YEAR; month++)
{
accounts[num].accountBal = (accounts[num].accountBal * accounts[num].annualInterest) + accounts[num].accountBal;
}
int month = 1;
cout << endl << "Total amount for account # " << (num + 1) << " is: " << accounts[num].accountBal << endl ;
total += accounts[num].accountBal;
cout << endl << "The total amount of all accounts is: " << total << endl;
}
}
average = total / NUM_OF_ACCOUNTS;
cout << "Average of all the bank accounts is: " << average << endl;
}
void BankAccount :: displayAccounts(BankAccount *accounts)
{
int input = 0;
int found;
const int MAX_ACCOUNTS = 100;
int quit = 0;
cout << endl << "Which account do you want to access?" << endl <<
"To stop or look at none of the account numbers type: " << quit << endl;
cin >> input;
for(int num = 0; num < MAX_ACCOUNTS; num++)
{
while(num < MAX_ACCOUNTS && input != accounts[num].accountNum)
{
num++;
}
if(input == accounts[num].accountNum) // This if sees if an account matches what the user entered.
{
cout << "Account: " << accounts[num].accountNum << endl << "Balance is: " <<
accounts[num].accountBal << endl << "Interest rate is: " << accounts[num].annualInterest;
cout << endl << "Enter another account number or type 0 to quit." << endl;
found = 1;
cout << endl;
cin >> input;
}
if(found == 0)
{
cout << "Sorry that account doesn't exist. Enter another account number." << endl;
cin >> input;
}
}
}
In C++, classes and structs are exactly the same constructs. They are, in fact, one thing — a User-Defined Type.
There is a different that is invoked depending on whether you used the keyword struct or class to define your UDT, and that is that class-key defaults to private member access and private inheritance, whereas struct-key defaults to both being public.
Other than this syntax difference, you can use either without worrying about one being "simpler" than the other.
Anyway, your compiler error (please provide it next time) is probably due to a declaration/definition mismatch.
Your declaration:
void displayAccounts(BankAccount *accounts, const int QUIT);
Start of your definition:
void BankAccount :: displayAccounts(BankAccount *accounts) {
The start of the definition should be
void BankAccount::displayAccounts(BankAccount* accounts, const int QUIT) {
to match. I've also fixed your spacing to be nicer. :)
void displayAccounts(BankAccount *accounts, const int QUIT);
... looks different between declaration and definition. Second parameter is missing in the definition.
Not sure what your question is, but classes and structs in C++ are equivalent except that fields are public by default in structs, but private by default in classes.
In the struct’s displayAccounts() member declaration you have:
void displayAccounts(BankAccount *accounts, const int QUIT);
and when defining the method later:
void BankAccount :: displayAccounts(BankAccount *accounts)
You have just missed
const int QUIT
parameter for the member function definition.