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.
Related
I have a simple program that calculates for mpg using arrays and pointers
When I input miles, it works perfectly but when i input gallons I can only input until 5th. any advice?
At first when it was still a for loop it was until 3rd only but when i used try and catch it was until 5th
I tried changing ctr value after the first for loop where i inputted miles but it didnt change. I tried using do while and while loop and still
const int size = 10;
typedef double *pointers;
void Mperg();
void MilesPerrGallon(double *ptr1, double *ptr2);
char displayMenu(char *pt);
int main()
{
char sagot;
char *ptr;
ptr =& sagot;
displayMenu(ptr);
switch(sagot){
case '1':
Mperg();
break;
case '2':
cout << "toit";
break;
default:
cout << sagot << " is invalid";
break;
}
}
void Mperg(){
double miles[size], gallons[size];
int ctr;
pointers milPtr, galPtr;
system("cls");
cout<<"COMPUTING FOR MPG : miles per gallon...\n";
cout<<"MILES\n";
galPtr = &gallons[size];
milPtr = &miles[size];
for(ctr = 0; ctr<size; ctr++){
try{
cout << "miles[" << ctr << "]: ";
cin >> milPtr[ctr];
if(milPtr[ctr] < 100 || milPtr[ctr] > 250){
throw milPtr[ctr];
}
}
catch(double xmilPtr){
cout << milPtr[ctr] << " is invalid!.. 100-250 only\nreenter new value\n";
ctr--;
}
}
system("cls");
do{
for(ctr = 0; ctr<size; ctr++){
try{
cout << "gallons[" << ctr << "]: ";
cin >> galPtr[ctr];
if(galPtr[ctr] < 5 || galPtr[ctr] > 25){
throw galPtr[ctr];
}
}
catch(double xgalPtr){
cout << galPtr[ctr] << " is invalid!.. 5-25 only\nreenter new value\n";
ctr--;
}
}
}while(ctr<size);
}
char displayMenu(char *pt)
{
//add code here
cout << "---------O P T I O N S---------\n";
cout << "[1] Compute Miles Per Gallon" << endl;
cout << "[2] Sorting of Numbers" << endl;
cout << "[3] EXIT" << endl;
cout << "-------------------------------\n";
cout << "Enter your choice: ";
cin >> *pt;
return *pt;
}
Miles
Gallons
galPtr = &gallons[size];
milPtr = &miles[size];
Since size is 10, this:
Sets galPtr to point to the 11th element of gallons.
Set milPtr to point to the 11th element of miles.
That's what the above code means in C++.
Of course, both arrays have only ten values, and attempting to obtain a pointer and using the pointer to modify the 11th, and subsequent, values in both arrays is undefined behavior.
You obviously meant to implement galPtr=gallons and milPtr=miles, here, although there is no real reason to use pointers this way, it doesn't accomplish anything.
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!
As part of a school assignment, I need to build a modular calculator with at least four modules (getData, getInteger, processData, displayData) doing add/subtract/multiply/divide/modulus operations on two integers.
I'm getting pretty stumped on putting this thing together, and I think it's largely because I'm struggling to understand how inter-function calls work (e.g. one function sending information to another function).
I've got the getInteger function getting integer input from the user, and I'm using processdata(intA, intB); to send this to the processData(int, int) function; but my getData(int) function also needs to send an integer input to processData - however processData(select) isn't valid because it doesn't have enough arguments. (I don't really understand what this means)
This is probably a bit confusing, so I've got the whole (unfinished/wip/doesn't actually work) program here:
//calculator program
//4 modules required: getData, getInteger, processData, displayData
#include <iostream> //To input/output to the display (I think)
#include <conio.h> //For getch() at end of program
using namespace std;
//prototypes
void getInteger(int, int);
void getData(int);
void processData(int, int);
void displayData(); // haven't added anything yet
int main(){
//prevents window from immediately closing
getch();
return 0;
}
void getInteger(int, int) {
int intA, intB;
cout << "Please enter integer one: " << endl;
cin >> intA;
cout << "Please enter integer two: " << endl;
cin >> intB;
processData(intA, intB); //sends info to processData function
}
void getData(int) {
int select;
cout << "Available Functions" << endl;
cout << "1. Addition (+)" << endl;
cout << "2. Subtraction (-)" << endl;
cout << "3. Multiplication (*)" << endl;
cout << "4. Division (/)" << endl;
cout << "5. Modulus (%)" << endl;
cout << "Please type your selection (1-5): " << endl;
cin >> select;
if (select > 5 || select < 1) {
cout << "Error: Out of Bounds, please re-enter your selection: " << endl;
cin >> select;
}
processData(select); //sends info to processData function
}
void processData() {
int add, sub, mul, div, mod, select, intA, intB;
switch(select) {
case 1:
select = 1; //addition
add = (intA + intB);
displayData(add); //sends info to displayData function
break;
case 2:
select = 2; //subtraction
sub = (intA - intB);
displayData(sub);
break;
case 3:
select = 3; //multiplication
mul = (intA * int B);
displayData(mul);
break;
case 4:
select = 4; //division
div = (intA / intB);
displayData(div);
break;
case 5:
select = 5; //modulus
mod = (intA % intB);
displayData(mod);
break;
default:
cout << "There's been an error :(" << endl;
}
return 0;
}
void displayData() {
}
Am I doing this all backwards? I feel like it'd be a lot easier if I could contain this in fewer functions, but it's mandatory to keep it in (at least) 4.
Your declarations and definitions are not matching with the arguments that you are passing. i.e. void processData() is in your definition, but you declare it void processData(int, int);
The traditional approach for this problem is to collect all the data needed in some way, then call the function to do the work. For your case, you'd have to figure out the select value, and then the intA and intB values [1], then pass all three into processData.
The other opption is to chain the calls together, so ask for the select value first, then pass the select to the function that reads the data, and call the processData from there.
So you would end up with something like this:
void getInteger(int select)
{
cout << "Please enter integer one: " << endl;
cin >> intA;
cout << "Please enter integer two: " << endl;
cin >> intB;
processData(select, intA, intB);
}
void processData(int select, int intA, int intB)
{
... code goes here...
}
I'm intentionally NOT writing the complete code - the way to learn programming is to DO things for yourself. Copy-n-paste is something you probably already can do.
[1] This is a bit problematic, a function can only return one thing. Since you have two different values to return, that's not going to work. An experienced programmer would either use reference-arguments, or return a structure containing both values, but my guess is that's part of what you are learning in a future lesson, so let's skip that idea.
Here is a working version of your code... Take note of the changes and also take notice to the use of pointers in getInteger(int*,int*)
Hope this helps you out!
#include <iostream> //To input/output to the display (I think)
#include <conio.h> //For getch() at end of program
using namespace std;
//prototypes
void getInteger(int*,int*);
void getData();
void processData(int, int, int);
void displayData(int); // haven't added anything yet
int main(){
getData();
return 0;
}
void getInteger(int *ptrA, int* ptrB) {
*ptrA = 0; //safety
*ptrB = 0; //safety
int tempA = 0;
int tempB = 0;
cout << "Please enter integer one: " << endl;
cin >> tempA;
cout << "Please enter integer two: " << endl;
cin >> tempB;
*ptrA = tempA;
*ptrB = tempB;
}
void getData() {
int select = 100;
while(select != 0){
cout << "Available Functions" << endl;
cout << "0. Exit program" << endl;
cout << "1. Addition (+)" << endl;
cout << "2. Subtraction (-)" << endl;
cout << "3. Multiplication (*)" << endl;
cout << "4. Division (/)" << endl;
cout << "5. Modulus (%)" << endl;
cout << "Please type your selection (1-5): " << endl;
cin >> select;
if (select > 5 && select > 0) {
cout << "Error: Out of Bounds, please re-enter your selection: " << endl;
cin >> select;
}else if(select == 0){
break;
}
int intA, intB; //these are set in the following void
getInteger(&intA, &intB);
processData(intA, intB, select); //sends info to processData function
}
}
void processData(int intA, int intB, int select) {
int add, sub, mul, div, mod;
switch(select) {
case 1:
select = 1; //addition
add = (intA + intB);
displayData(add); //sends info to displayData function
break;
case 2:
select = 2; //subtraction
sub = (intA - intB);
displayData(sub);
break;
case 3:
select = 3; //multiplication
mul = (intA * intB);
displayData(mul);
break;
case 4:
select = 4; //division
div = (intA / intB);
displayData(div);
break;
case 5:
select = 5; //modulus
mod = (intA % intB);
displayData(mod);
break;
default:
cout << "There's been an error :(" << endl;
}
// return 0; void does not return
}
void displayData(int result){
cout << "The result is: " << result << endl;
}
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
/*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.