Object is initializing to unwanted value - c++

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".

Related

Doing while loop properly until "0" input to stop the loop?

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!

'Vehicle' is not valid template type argument for parameter '_Ty'

VS keeps giving me the error mentioned in the title for every function for a class project (at least, all of the ones in Vehicle.h), and I can't figure it out no matter how hard I try. It doesn't seem to be due to any circular definitions, but maybe the answer is simple. The project is supposed to be based on four files (two header files and two .cpp's); I'll attach them below.
Vehicle.h:
#include <iostream>
#include <fstream>
#include <string>
#include<vector>
using namespace std;
//Declaring Dealer class
class Dealer
{
public:
Dealer();
int getDealerNum();
void setDealerNum(int dealerNumber);
private:
int dealerNumber;
Dealer *dealer;
};
//Declaring Vehicle class
class Vehicle
{
public:
Dealer *dealerType;
Vehicle(string VIN, string make, string model, int year, double price);
Vehicle();
string getVIN();
string getMake();
string getModel();
int getYear();
double getPrice();
void setVIN(string VIN);
void setMake(string make);
void setModel(string model);
void setYear(int year);
void setPrice(double price);
friend Vehicle;
private:
string VIN;
string make;
string model;
int year;
double price;
};
Functions.h (only one function included, to save some space):
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include<string>
#include<vector>
using namespace std;
//Declaring name for input and output file
ofstream outfile;
ifstream infile;
void displayInventory(vector<Vehicle>& vehicles)
{
int i = 0;
char query = 'a';
int j = vehicles.size();
//Simple loop to display the inventory, with a pause function to wait for user exit
while (query != 'x'&&query!='X')
{
for (i; i < j; i++)
{
cout << "Vehicle #" << i + 1 << endl;
cout << "Vin: " << vehicles[i].getVIN << endl;
cout << "Make: " << vehicles[i].getMake << endl;
cout << "Model: " << vehicles[i].getModel << endl;
cout << "Year: " << vehicles[i].getYear << endl;
cout << "Price: $" << vehicles[i].getPrice << endl << endl;
}
cout << endl << "Enter 'x' to return to main menu" << endl;
cin >> query;
cout << endl;
}
}
Main.cpp:
#include <iostream>
#include <fstream>
#include <string>
#include<vector>
#include "Thomas-PA3 Functions.h"
#include "Thomas-PA3 Vehicle.h"
using namespace std;
void displayInventory(vector<Vehicle>& vehicles);
void addInventory(vector<Vehicle>& vehicles);
void deleteInventory(vector<Vehicle>& vehicles);
void updateInventory(vector<Vehicle>& vehicles);
void sortInventory(vector<Vehicle>& vehicles);
void searchInventory(vector<Vehicle>& vehicles);
void writeInventory(vector<Vehicle>& vehicles);
void refreshInventory(vector<Vehicle>& vehicles);
int main()
{
char menu='0';
vector<Dealer>dealers;
vector<Vehicle>vehicles;
while(menu!='8')
{
cout << "Welcome to the vehicle management menu." << endl;
cout << "Please select an option from the following list:" << endl;
cout << "1: Display vehicles" << endl;
cout << "2: Add a vehicle" << endl;
cout << "3: Update a vehicle" << endl;
cout << "4: Delete a vehicle" << endl;
cout << "5: Sort inventory by VIN" << endl;
cout << "6: Search inventory by Make" << endl;
cout << "7: Read inventory from file (will overwrite any changes)" << endl;
cout << "8: Write inventory to file and exit" << endl;
cin >> menu;
switch(menu)
{
// Call to appropriate functions based upon user decision
case '1': displayInventory(vehicles);
break;
case '2': addInventory(vehicles);
break;
case '3': updateInventory(vehicles);
sortInventory(vehicles);
break;
case '4': deleteInventory(vehicles);
break;
case '5': sortInventory(vehicles);
break;
case '6': searchInventory(vehicles);
break;
case '7': refreshInventory(vehicles);
break;
case '8': sortInventory(vehicles);
writeInventory(vehicles);
break;
//Error/incorrect input checking
default: cout << endl << "Please make a valid selection" << endl << endl;
}
}
return 0;
}
Vehicle.cpp:
#include <iostream>
#include <fstream>
#include <string>
#include<vector>
#include "Thomas-PA3 Vehicle.h"
#include "Thomas-PA3 Functions.h"
using namespace std;
//Default constructor for Dealer
Dealer::Dealer()
{
dealerNumber = 0;
}
//Function to get dealer number
int Dealer::getDealerNum()
{
return dealerNumber;
}
void Dealer::setDealerNum(int dealerNumber)
{
cout << "Please input the new dealer number" << endl;
cin >> dealerNumber;
}
//Custom constructor for Vehicle
Vehicle::Vehicle(string VIN, string make, string model, int year, double price)
{
cout << "Vehicle data is initialized" << endl;
}
//Default constructor for Vehicle
Vehicle::Vehicle()
{
VIN = "0";
make = "";
model = "";
year = 0;
price = 0;
}
//Functions to return member variables
string Vehicle::getVIN()
{
return VIN;
}
string Vehicle::getMake()
{
return make;
}
string Vehicle::getModel()
{
return model;
}
int Vehicle::getYear()
{
return year;
}
double Vehicle::getPrice()
{
return price;
}
//Functions to set member variables
void Vehicle::setVIN(string VIN)
{
cout << "Please input the vehicle's VIN #" << endl;
cin >> VIN;
}
void Vehicle::setMake(string make)
{
cout << "Please input the vehicle's make" << endl;
cin >> VIN;
}
void Vehicle::setModel(string model)
{
cout << "Please input the vehicle's model" << endl;
cin >> VIN;
}
void Vehicle::setYear(int year)
{
cout << "Please input the vehicle's year" << endl;
cin >> VIN;
}
void Vehicle::setPrice(double price)
{
cout << "Please input the vehicle's price" << endl;
cin >> VIN;
}
You include "Functions.h" before "Vehicles.h". Therefore, when the compiler sees vector<Vehicle>, it doesn't yet know that Vehicle will be defined as a class later.
C++ is compiled in three stages. First, the preprocessor runs and executes #include statements and the like. This is done once per .cpp file, and the result is fed to the real compiler. The compiler then compiles this result line by line. Finally, the linker glues everything together.
The important stage here is the middle one. Because each .cpp file is compiled in isolation, top to bottom, you put the necessary headers at the top. And if one header needs another, you put one above the other. To make this easy, it can be useful to #include one header in the other. After all, all the #include statements are executed. Everything ends up in the .cpp file eventually.
One final remark: You generally need to protect yourself against double #includes. There's a second preprocessor mechanism for that: surround your .h file with
#ifndef VEHICLE_H
#define VEHICLE_H
// Real contents of Vehicle.h go here, including any other #include statement
#endif
If you now write
#include "vehicle.h"
//.. other stuff
#include "vehicle.h"
the preprocessor will see the second statement, and note that VEHICLE_H was already defined, so the second inclusion is not needed. Spelling note: it's all uppercase to prevent confusion with class Vehicle and other similar names, and you can't use a . there so the suffix is _H.

Simple bank account program does not store the balance correctly

I'm currently wrapping up my bank account program, but I've ran into some problems en route to completion. The problem seems pretty easy to resolve, but I can't quite wrap my head around how I should go about actually fixing it.
I'll first include the assignment below:
Implement a class Account. An account has a balance, functions to add and withdraw money, and a function to inquire the current balance. Pass a value into a constructor to set an initial balance.
If no value is passed the initial balance should be set to $0.
Charge a $5 penalty if an attempt is made to withdraw more money than available in the account.
Enhance the Account class to compute interest on the current balance.
Implement a class Bank. This bank has two objects, checking and savings, of the type Account that was developed in the preceding exercise.
Implement four instance methods:
deposit(double amount, String account)
withdraw(double amount, String account)
transfer(double amount, String account)
printBalances()
Here the account string is "S" or "C". For the deposit or withdrawal, it indicates which account is affected. For a transfer it indicates the account from which the money is taken; the money is automatically transferred to the other account.
The only problem appears to be with actually storing the information for each account in the balance variable in the Account.cpp file. It just stays at 0, and that's why I feel this issue should be easy to fix. I'd imagine I'm just forgetting something very basic about class implementations, but that is why I am here! Now that I think about it, I think part of my confusion comes from the fact that I've implemented similar programs before but used only arrays instead of variables, and I did not experience this same problem. The data seemed to get stored into the array regardless, so this may be my problem? The code follows:
Account.h:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class Account
{
public:
Account();
Account(double balance);
void Add(double money);
void Withdraw(double money);
double GetBalance();
private:
double balance;
};
Account.cpp:
#include "Account.h"
// Penalty Fee Constant
const double PENALTY_FEE = 5.00;
Account::Account()
{
balance = 0.00;
}
Account::Account(double money)
{
balance = money;
}
void Account::Add(double money)
{
balance += money;
}
void Account::Withdraw(double money)
{
if(money > balance)
balance += PENALTY_FEE;
else
balance -= money;
}
double Account::GetBalance()
{
return balance;
}
Bank.cpp:
#include "Account.h"
void deposit(double, string);
void withdraw(double, string);
void transfer(double, string);
void printBalances();
int main()
{
string accountChoice;
int selection;
double transaction = 0;
// !!!!!!!!!!!!!!!!!!HAVE TO STILL COMPUTE INTEREST!!!!!!!!!!!!!!!!
cout << fixed << showpoint << setprecision(2);
do
{
cout << "Please make a selection:" << endl;
cout << "1.) Deposit" << endl;
cout << "2.) Withdraw" << endl;
cout << "3.) Transfer" << endl;
cout << "4.) Print balances" << endl;
cout << "5.) Quit" << endl;
cin >> selection;
if(selection == 1)
{
cout << endl << "Please select the account you would like to perform operations on(S or C):" << endl;
cin >> accountChoice;
cout << endl << "Please enter the amount to be deposited:" << endl;
cin >> transaction;
cout << endl;
deposit(transaction, accountChoice);
}
else if(selection == 2)
{
cout << endl << "Please select the account you would like to perform operations on(S or C):" << endl;
cin >> accountChoice;
cout << endl << "Please enter the amount to be withdrawn:" << endl;
cin >> transaction;
cout << endl;
withdraw(transaction, accountChoice);
}
else if(selection == 3)
{
cout << endl << "Please select the account you would like to perform operations on(S or C):" << endl;
cin >> accountChoice;
cout << endl << "Please enter the amount to be transferred:" << endl;
cin >> transaction;
cout << endl;
transfer(transaction, accountChoice);
}
else if(selection == 4)
printBalances();
else
cout << "Closing program -- Thank you for using the ATM teller!" << endl;
}while(selection != 5);
system("pause");
return 0;
}
void deposit(double amount, string account)
{
Account savings, checking;
if(account == "S" || account == "s")
savings.Add(amount);
else
checking.Add(amount);
}
void withdraw(double amount, string account)
{
Account savings, checking;
if(account == "S" || account == "s")
savings.Withdraw(amount);
else
checking.Withdraw(amount);
}
void transfer(double amount, string account)
{
Account savings, checking;
if(account == "S" || account == "s")
{
savings.Withdraw(amount);
checking.Add(amount);
}
else
{
checking.Withdraw(amount);
savings.Add(amount);
}
}
void printBalances()
{
Account savings, checking;
cout << "The current balance in savings is: " << savings.GetBalance() << endl;
cout << "The current balance in checking is: " << checking.GetBalance() << endl << endl;
}
I think it might be clearer overall if you declare another class 'Customer', and give them a name, customer number and a checking and saving account each. The Customers should be instantiated somewhere with process lifetime so that they are not deleted, eg. in a static container, eg std::map.
ATM, (sorry!), you seem to have some non-member functions that instantiate accounts, do things with them and then they are deleted upon function return.
You are creating a new Account object every time you need it. Of course it will be 0 when you print it as the default constructor initializes the balance to 0.
Rather when the App starts, as the user to identify his account or something and create a corresponding account instance. The instance need to be there throughout the whole time user operates on it.
So instantiate not in the methods but in the main function. And pass the instance to the methods as a way of modifying the instance as required.

Reading from/writing to files using functions [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Hi I am working on a simple wage application. The following code contains a two option menu using switch statements. The code is also linked to a text file called "shop-account". The file simply contains the value 100.
For option 1 the user is suppose to be able to transfer an amount from the file. The user should be able to make as many transfers as they choose without overdrawing the account. And the code should be able to output the current balance. I believe I am suppose to be using the void function but I have never used it before and am really struggling. I was hoping someone could look at the code and tell me where I am going wrong. Thanks
int read_balance (void);
void write_balance (int balance);
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int selection;
int total;
int balance;
int NewAmount;
do {
cout << "1. Transfer an amount" <<endl;
cout << "2. Quit" << endl;
cout << "Please enter menu number"<<endl;
cin >> selection;
switch(selection)
{
case 1:
cout << "You have choosen to transfer an amount" << endl;
cout << "How much do you wish to transfer from the shop account?"<<endl;
cin >> NewAmount;
balance -= NewAmount;
write_balance (balance);
cout << balance << endl;
break;
case 2:
return 0;
break;
default:
cout << "Ooops, invalid selection!" << endl;
break;
}
}while(selection != 2);
system("pause");
return 0;
}
int read_balance (void)
{
fstream f;
f.open("shop-account.txt");
f >> balance; //error: "balance" is unidentified
f.close();
return balance;
}
void write_balance (int balance)
{
fstream f;
f.open("shop-account.txt");
f << balance;
f.close();
}
Like others mentioned, you didn't declare the int balance in the right scope (function level scope, in this case).
In fact, it looks like you forgot call read_balance alltogether, so your calculations on balance used an indeterminate value, which is Undefined Behaviour.
Next up: declare your variables where they are used, that way you prevent this whole situation when you decide to extract pieces of code into subfunctions, and it gets easier to see where variables are used. Consequently, it gets easier to see whether the code is correct.
Next: Error handling. If you have none, your program is worthless. In fact, even when fixing the above issue,
simply entering invalid input once would run a loop and just keep substracting indeterminate values from the account balance and writing those wrong values to disk. That's probably not what you wanted.
making the shop-account.txt read-only was enough to fool the program into
transfer unlimited amounts without updating the file
having the wrong idea of the balance in the file (since it never checks)
Here is a cleaned-up version that does a minimum amount of checking, and adds an option to just 'check the account balance'. Seemed useful.
See it Live On Coliru
I hope some of this helps. For one thing, I hope your teacher was going to mention most of this :/
int read_balance(void);
void write_balance(int balance);
#include <iostream>
#include <limits>
int main()
{
while(std::cin.good())
{
std::cout << "0. Request balance" << std::endl;
std::cout << "1. Transfer an amount" << std::endl;
std::cout << "2. Quit" << std::endl;
std::cout << "Please enter menu number" << std::endl;
int selection = 2;
if(std::cin >> selection)
{
std::cout << "DEBUG: selection:" << selection << "\n";
switch(selection)
{
case 0:
std::cout << "The current account balance is " << read_balance() << std::endl;
break;
case 1:
{
std::cout << "You have choosen to transfer an amount" << std::endl;
std::cout << "How much do you wish to transfer from the shop account?"<<std::endl;
int amount = 0;
if (std::cin >> amount)
{
std::cout << "DEBUG: amount:" << amount << "\n";
int balance = read_balance();
if(amount<=0)
{
std::cout << "Amount must be positive\n";
}
else if(balance < amount)
{
std::cout << "Insufficient funds\n";
}
else
{
int new_balance = balance - amount;
write_balance(new_balance);
std::cout << "New account balance: " << new_balance << std::endl;
}
} else
{
// bad input cleared outside the switch
}
}
break;
case 2:
return 0;
break;
default:
std::cout << "Ooops, invalid selection!" << std::endl;
break;
}
}
if(std::cin.eof())
{
std::cout << "Bye\n";
return 0;
}
if(std::cin.fail())
{
std::cin.clear();
std::cin.ignore(99999, '\n');
std::cout << "Invalid input\n";
// note eof() can be true here
}
}
}
#include <fstream>
int read_balance(void)
{
std::ifstream f;
f.exceptions(std::ios::failbit | std::ios::badbit);
f.open("shop-account.txt");
int balance;
f >> balance;
f.close();
return balance;
}
void write_balance(int balance)
{
std::ofstream f;
f.exceptions(std::ios::failbit | std::ios::badbit);
f.open("shop-account.txt");
f << balance;
f.close();
}
your function does not have a balance varible declartion !! you have to add a balance declaration in your function
int read_balance(void)
{
fstream f;
f.open("shop-account.txt");
int balance;
f >> balance; //now it's defined
f.close();
return balance;
}

Trying to call functions from class

I am trying to execute the code inside of a .h File by creating an object.. What am I doing wrong?
//TicketFineCalculator.h
#include <iostream>
using namespace std;
class TicketFineCalculator
{
public:
int getFine() {
int procFee, zone, speedLimit, actualSpeed, totalFine;
int anotherRun = 1;
while (anotherRun == 1){
cout << "\n-------------------------------";
cout << "\nSpeeding Ticket Fine Calculator";
cout << "\n-------------------------------";
cout << "\nEnter processing fee, in dollars:";
cin >> procFee;
cout << "\nSpeeding Ticket #1";
cout << "\nEnter the type of speeding offense (1 for regular, 2 for work zone, 3 for residential district):";
cin >> zone;
cout << "\nEnter the speed limit, in miles per hour:";
cin >> speedLimit;
cout << "\nEnter the vehicle's speed, in miles per hour:";
cin >> actualSpeed;
cout << "\nThe total fine is:" << totalFine;
cout << "\nEnter 1 to enter process another speeding ticket or 0 to quit:";
cin >> anotherRun;
} // terminates while loop
return totalFine;
}
// Calculate the total fine given the road zone, speed limit, and the vehicle's actual speed.
// Return the fine as an integer.
};
//Project1.cpp
#include <iostream>
#include "TicketFineCalculator.h"
int totalFine;
TicketFineCalculator::getFine(totalFine);
int main(){
cout << totalFine;
return 0;
} //terminates main
If you want to call the getFine() method within TicketFineCalculator, you must declare the method static as in:
class TicketFineCalculator
{
public:
static getFine()
{
}
};
or you must create an instance of TicketFineCalculator and call the method using that instance.