I have a base class called account. Three classes are inheriting from account. These classes are savings, checkings, and creditcard. In my main() I am trying to create a switch menu so that when the user selects 1 it will call makeDeposit(), which is part of account, but do so through savings. This way when the user chooses 3 it will call makeDeposit(), but do so through checkings. Here is the code I have written. I have declared object saving sa; and when I call makeDeposit I am trying to write it as sa.makeDeposit(). Here is the code:
int main ()
{
saving sa;
creditCard cca;
checking ca;
string n;
int option;
int exit = 1;
cout << endl;
cout << "Checking Balance:" << " " << " " << "Savings balance:" << " " << " " << "Credit Card balance:" << " " << endl;
cout << endl;
cout << " (1) Savings Deposit " << endl;
cout << " (2) Savings withdrawel " << endl;
cout << " (3) Checking Deposit " << endl;
cout << " (4) Write A Check " << endl;
cout << " (5) Credit Card Payment " << endl;
cout << " (6) Make A Charge " << endl;
cout << " (7) Display Savings " << endl;
cout << " (8) Display Checkings " << endl;
cout << " (9) Display Credit Card " << endl;
cout << " (0) Exit " << endl;
cin >> option;
do{
switch ( option )
{
case 1 : double amtD;
cout << " Please enter how much you would like to deposit into savings " << endl;
cin >> amtD;
double sa.makeDeposit(double amtD);
break;
case 2 : double makeWithdrawel();
break;
case 3 : double makeDeposit();
break;
case 4 :
break;
case 5 :
break;
case 6 : double makeWithdrawel();
break;
case 7 : int display();
break;
case 8 : int display();
break;
case 9 : int display();
break;
case 0 : exit = 0;
break;
default : exit = 0;
cout << " ERROR ";
}
}
while(exit==1);
return 0;
}
Here is my class saving :
#include "stdafx.h"
#include "iostream"
#include "Account.h"
#include <string>
#include <sstream>
using namespace std;
class saving: public account
{
public :
double doWithdraw(double amount);
saving();
saving(string itsName, long itsTaxID, double itsBalance);
}
and my class for account :
#include "stdafx.h"
#include <string>
#include <sstream>
using namespace std;
class account {
public :
void setName(string name); void setTaxID(long taxID); void setBalance(double balance);
string getName(); long getTaxID(); double getBalance();
double makeDeposit( double amount );
account();
account(string itsName, long itsTaxID, double itsBalance);
int display();
private :
string itsName;
long itsTaxID;
double itsBalance;
protected :
double last10withdraws[10];
double last10deposits[10];
int numdeposits;
int numwithdraws;
};
Any idea on what I am doing wrong??
You're calling functions incorrectly. You do not need to include the types for the return value and parameters.
case 10: int function(); break;
is actually declaring a local function - not calling function as you expect.
Your switch statement should look something like below. Notice the absence of types in the calls to functions
switch ( option )
{
case 1 : double amtD;
cout << " Please enter how much you would like to deposit into savings " << endl;
cin >> amtD;
sa.makeDeposit(amtD);
break;
case 2 : makeWithdrawel();
break;
case 3 : makeDeposit();
break;
case 4 :
break;
case 5 :
break;
case 6 : makeWithdrawel();
break;
case 7 : display();
break;
case 8 : display();
break;
case 9 : display();
break;
case 0 : exit = 0;
break;
default : exit = 0;
cout << " ERROR ";
}
The following code looks a bit weird.
cin >> amtD;
double sa.makeDeposit(double amtD);
break;
You are trying to declare a variable with the double keyword, but I think you want to do one of two things:
Just make the deposit without using the returned double from makeDeposit() for anything. In that case, just write the line like this (using the returned double is optional):
sa.makeDeposit(amtD);
You want to make the deposit but also save some return information. Then you would probably do something like this (and use the new variable for something later).
double justMadeDeposit = sa.makeDeposit(amtD);
It's some guesswork. Maybe you don't want the makeDeposit() function to return anything at all, and then you could declare it as void instead.
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!
I am unable to understand as to why the switch block is not executed. I am trying to generate random numbers between 0 and 2 using rand() within comp_in() function. I return the number to the main function. Within the main function, I am trying to associate a char to each letter generated. The switch statement is not executed at all. Please help!
#include<iostream>
using namespace std;
int comp_in();
int main()
{
char h;
h = human_in();
int c = comp_in();
cout << "c is" << c << endl;
switch(c)
{
case '0' : cout << "Computer's choice is : 'R'" << endl;
break;
case '1' : cout << "Computer's choice is : 'P'" << endl;
break;
case '2' : cout << "Computer's choice is : 'S'" << endl;
break;
}
}
int comp_in()
{
int s;
for(int i=0; i<4; i++)
{
s=rand()%3;
}
cout << "s is : " << s << endl;
return s;
}
Output:-
s is : 1
c is1
The problem is that your comp_in function returns numbers, but your switch is comparing its result to characters. Simply remove the single quotes from each case, making them numbers, and it'll work:
switch(c)
{
case 0 : cout << "Computer's choice is : 'R'" << endl;
break;
case 1 : cout << "Computer's choice is : 'P'" << endl;
break;
case 2 : cout << "Computer's choice is : 'S'" << endl;
break;
default: cout << "Computer made a really strange choice: " << c << endl;
break;
}
Do note that at some point in the future, you might want to compare the human input with the computer input. Since your human_in function returns a character, you're going to have to convert it by using a function like atoi.
You can detect bugs like these more quickly if you output some sort of debug message in a default case, which I've also included in the code sample above.
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;
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
undefined reference to `WinMain#16'
I am building an application that calculates travel time necessary to reach a user selected destination from predetermined city based upon an estimated travel speed determined by the user. For this program I am to utilize classes/class source files. When compiling my source file I continuously get the error “undefined reference to `WinMain#16’” and due to my being unfamiliar with the usage of source files I am not sure how to fix this issue. Any help would be appreciated with regard to pointing me in the right direction as to properly utilizing source files. Thanks in advance for the help.
Header file:
#include <iostream>
using namespace std;
class Trip
{
private:
string destination;
double distance;
public:
void TripValue(string b, double c);
void TripTime(Trip *a);
};
Source File:
#include "Trip.h"
#include <iostream>
using namespace std;
void Trip::TripValue(string b, double c)
{
destination = b;
distance = c;
}
void Trip::TripTime(Trip *a)
{
double user_speed;
double time;
cout << "Please enter your estimated travel speed in miles per hour: ";
cin >> user_speed;
cout << endl;
time = (a->distance / user_speed);
cout << endl;
cout << "Your estimated travel time to " << a->destination << " is "
<< time << " hours.\n";
cout << endl;
}
Application code:
#include <iostream>
#include "Trip.h"
using namespace std;
int main()
{
Trip StL, Indy, Det, Nash, Dal, Den, NY, LA, Mia, Sea;
int choice;
StL.TripValue("St. Louis", 297.34);
Indy.TripValue("Indianapolis", 184.78);
Det.TripValue("Detroit", 282.73);
Nash.TripValue("Nashville", 441.02);
Dal.TripValue("Dallas", 925.91);
Den.TripValue("Denver", 1004.93);
NY.TripValue("New York", 791.50);
LA.TripValue("Los Angeles", 2017.74);
Mia.TripValue("Miami", 1363.55);
Sea.TripValue("Seattle", 2032.31);
do
{
cout << "=================================Trip Calulator=================================\n";
cout << "Select your destination from Chicago:\n";
cout << endl;
cout << " 1. St. Louis\n";
cout << " 2. Indianapolis\n";
cout << " 3. Detroit\n";
cout << " 4. Nashville\n";
cout << " 5. Dallas\n";
cout << " 6. Denver\n";
cout << " 7. New York\n";
cout << " 8. Los Angeles\n";
cout << " 9. Miami\n";
cout << "10. Seattle\n";
cout << endl;
cout << " 0. Exit\n";
cout << "================================================================================\n";
cin >> choice;
cout << endl;
switch (choice)
{
case 1:
StL.TripTime(&StL);
break;
case 2:
Indy.TripTime(&Indy);
break;
case 3:
Det.TripTime(&Det);
break;
case 4:
Nash.TripTime(&Nash);
break;
case 5:
Dal.TripTime(&Dal);
break;
case 6:
Den.TripTime(&Den);
break;
case 7:
NY.TripTime(&NY);
break;
case 8:
LA.TripTime(&LA);
break;
case 9:
Mia.TripTime(&Mia);
break;
case 10:
Sea.TripTime(&Sea);
break;
}
} while (choice != 0);
}
Thats a linker problem.
Try to change Properties -> Linker -> System -> SubSystem
from Windows (/SUBSYSTEM:WINDOWS) to Console (/SUBSYSTEM:CONSOLE)
I have been working on a trivial assignment to get used to coding. I am designing an ATM machine and at the moment it is composed of 2 classes:
BankAccount.cpp
Constructor for different types of account
Only has balance as a member
Transaction.cpp
Performs a method on the BankAccount (i.e make deposit, make withdrawl & get balance)
Problem: BankAccount is automatically initialized to a balance of 10 which is undesired. So for example, if I made a checking account and chose to deposit $10, balance would print out $20.
//BankAccount.h
//This class will simply take in a bank account
//with a balance, other classes will use a bank account object
//such as saving/checkings and perform operations on the
//balance
#ifndef BANK_ACCOUNT_H
#define BANK_ACCOUNT_H
class BankAccount {
private:
float balance;
public:
BankAccount ();
float getBalance ();
void makeDeposit ();
void makeWithdrawl ();
};
#endif
//BankAccount.cpp
#include "BankAccount.h"
#include <iostream> //remove once done *not to self
using namespace std; //remove once done *note to self
BankAccount::BankAccount() {
balance = 0.00;
}
float BankAccount::getBalance() {
return balance;
}
void BankAccount::makeDeposit() {
cout << "How much would you like to deposit: ";
float deposit_value;
cin >> deposit_value;
balance += deposit_value;
}
void BankAccount::makeWithdrawl() {
cout << "How much would you like to withdrawl: ";
float withdrawl_value;
cin >> withdrawl_value;
balance -= withdrawl_value;
}
//Transaction.h
#ifndef TRANSACTION_H
#define TRANSACTION_H
class Transaction {
private:
BankAccount m_bao;
public:
Transaction(BankAccount&);
void displayOptions();
void printReciept();
};
#endif
//Transaction.cpp
#include "BankAccount.h"
#include "Transaction.h"
#include <iostream>
using namespace std;
Transaction::Transaction(BankAccount& bao) {
m_bao = bao;
}
void Transaction::displayOptions() {
cout << "\nPlease make a choice\n\n";
cout << "1: Make Deposit\n";
cout << "2: Make Withdrawl\n";
cout << "3: Check Balance\n";
int choice;
cin >> choice;
switch (choice) {
case 1:
m_bao.makeDeposit();
break;
case 2:
m_bao.makeWithdrawl();
break;
case 3:
m_bao.getBalance();
break;
}
}
void Transaction::printReciept() {
cout << "Current balance is now: " << m_bao.getBalance() + '\n';
}
int main () {
BankAccount checking;
Transaction q(checking);
q.displayOptions();
q.printReciept();
}
I am sure the answer is right in front of my eyes, but my brain is just fried right now. I will continue to look for the solutions and let you guys know if my problem has been solved yet.
[EDIT]
Alright, now I am trying to make it so that the customer can choose to perform transactions on either Checking or Savings account. Currently I got it looking like this in my main():
int main () {
BankAccount checking(0.00);
BankAccount savings(0.00);
Transaction c(checking);
Transaction s(savings);
for(int i = 0; i < 10 ; i++) {
cout << "Make an option" << endl;
cout << "1. Checking " << endl;
cout << "2. Savings" << endl;
int choice;
cin >> choice;
if (choice == 1) {
c.prompt();
c.printReciept();
}
else {
s.prompt();
s.printReciept();
}
}
}
It works fine, but I would like to make this process more OOP-alized, if that makes sense :)
One option I was trying to look into was making a prompt function which would belong to Transaction.cpp. This would do everything that is done in main, except initializing the objects of course.
Your problem is this line:
cout << "Current balance is now: " << m_bao.getBalance() + '\n';
Which the compiler sees as:
cout << "Current balance is now: " << (m_bao.getBalance() + '\n');
'\n' is 10 as an int, so you get this:
cout << "Current balance is now: " << (m_bao.getBalance() + 10);
You probably meant to do this:
cout << "Current balance is now: " << m_bao.getBalance() << '\n';
Remember that in C++, + almost always means "add these two numbers".