I am creating a program which includes a parent class Account and a derived class BankAccount. Initially, I have to set the balance in account to be 5000. And when certain transactions are made, this balance should be updated. Also, whenever the program is closed, the program should return the latest balance. Below is my code. However, I am not able to initialize the constructor properly and hence, initial balance is never set correctly. Please tell me what I am doing wrong.
class Account
{
public:
void setCashBal(); //updates the cash balance in account whenever a transaction is made
double getCashBal(); //retrieves recent cash balance
protected:
double cash_balance;
};
void Account::setCashBal()
{
double initial_bal;
ifstream read_cash_file("cash_bal_file.txt", ios_base::in);
int count = 0;
if (read_cash_file.is_open()) //check whether the file could be openend
{
while (!(read_cash_file.eof())) //reading until the end of file
{
count = count + 1;
break;
}
read_cash_file.close();
if (count == 0)//if the file is opened the first time, initial cash balance is 5000
{
initial_bal = 5000;
ofstream write_cash_file("cash_bal_file.txt", ios::out);
write_cash_file << initial_bal; //writing the initial value of cash balance in cash_bal_file
write_cash_file.close();
read_cash_file.open("cash_bal_file.txt", ios_base::in);
read_cash_file >> cash_balance;
read_cash_file.close();
}
else //getting the latest cash balance
{
read_cash_file.open("cash_bal_file.txt", ios::in);
read_cash_file >> cash_balance;
read_cash_file.close();
}
}
else //case when the file could not be openend
cout << endl << "Sorry, cash_bal_file could not be opened." << endl;
}
double Account::getCashBal()
{
return cash_balance;
}
class BankAccount :public Account
{
public:
BankAccount();
void viewBalance();
};
BankAccount::BankAccount()
{
setCashBal();
cash_balance = getCashBal();
}
void BankAccount::viewBalance()
{
double balance;
ifstream view_bal("cash_bal_file.txt", ios_base::in); //getting the latest cash_balance from cash_bal_file.
view_bal >> balance;
cout << endl << "The balance in your bank account is " << balance << endl;
}
int main()
{
BankAccount bnkObj;
bnkObj.viewBalance();
return 0;
}
class Account
{
public:
int n;
Account(): n(5000)
{}
};
This is called "initializing a member variable in the constructor", or just "initializing". If you search an introductory C++ text for "initialize", you'll find something like this.
Related
I'm trying to write a program that simulates an ATM. The user can log in with a pin and account number, check their account balance, and make a withdrawal. I'm having trouble initializing the array that contains the account information, here's what I have so far:
#include <iostream>
#include <string>
using namespace std;
class Account
{
private: int accountNum;
string accountPin;
double balance;
void setPin();
void setAccountNum();
public: Account ()//default constructor
{
accountNum = -1;
accountPin = -1;
balance = 0.0;
};
Account (int accountNum, string accountPin, double balance)
//overloaded construtor
{
accountNum = accountNum;
accountPin = accountPin;
balance = balance;
};
void setAccountBalance(double bal);//acc balance setter
int getAccountNum() //acc balance getter
{
return balance;
}
bool confirmPin(string)//confirm pin# func
{
}
void updateBalance(double)
};
int main ()
{
int option;
//accounts array
Account account[]= (123, "abc123", 100.00), (456, "def456", 50.00),(789,"ghi789", 500.63);
//login code, unfinished
cout << "LOGIN\nEnter Account#: "<< endl;
cin >> accNum;
cout << "Enter pin#: "<<endl;;
getline(accPin);
//menu do while loop, unfinshed
do {
cout << "1. Check balance\n2.Make a deposit\n3.Logout\n";
cin >> option;
switch (option)
//check balance case
case 1:
// make a deposit case
case 2:
}
while (option !=3);
return 0;
}
Line 48 is where the array needs to be initialized, it contains the account number, the pin code, and the account balance (in that order). Can anyone point out the mistake I'm making? Thanks for the help in advance.
You need curly braces around the entire initializer list, and also around the initializer for each element.
Account account[]= {
{123, "abc123", 100.00},
{456, "def456", 50.00},
{789,"ghi789", 500.63}
};
I'm trying to processes values from two text files.One holds a set of chars and the other holds a set of integers.each in their respective places in the text file will amount to one test case.For example the first value that is read in each text file is 1 test case.The values are then used to be checked for variability then Which will then be used as variables through out my code.then in the end prints out a double. The issue is I do not know how to reach that second iteration of test cases. All my code does is read the first values of each text file and prints out the double i need but for only the first test case. As i was typing this out i thought of maybe deleting the values once they are done being used then rerunning the program by having my main in a for loop? suggestions?
#include <iostream>
#include <fstream>
using namespace std;
//function prototypes
char getPackage();
bool vaildPackage(char);
int getHours();
bool validHours(int);
double calculatePakg_A(int);
double calculatePakg_B(int);
double calculatePakg_C(int);
void showBill(double);
int main()
{
char Package = getPackage();
int Hours = getHours();
double bill;
switch (Package)
{
case 'A':bill = calculatePakg_A(Hours);
cout << bill << endl;
break;
case 'B':bill = calculatePakg_B(Hours);
cout << bill << endl;
break;
case 'C':bill = calculatePakg_C(Hours);
cout << bill << endl;
break;
case 'a':bill = calculatePakg_A(Hours);
cout << bill << endl;
break;
case 'b':bill = calculatePakg_B(Hours);
cout << bill << endl;
break;
case 'c':bill = calculatePakg_C(Hours);
cout << bill << endl;
break;
default: cout << "you did not enter a valid Service Plan. \n";
break;
}
return 0;
}
char getPackage()
{
ifstream inputFile;
char a;
inputFile.open("Packages.txt");
do
{
inputFile >> a;
} while (! vaildPackage(a));
return a;
}
bool vaildPackage(char a)
{
return a == 'a' || a == 'A'|| a == 'B' || a == 'b'|| a == 'C' || a == 'c';
}
int getHours()
{
ifstream inFile;
int n;
inFile.open("Hours.txt");
do
{
inFile >> n;
} while (! validHours(n));
return n;
}
bool validHours(int n)
{
return n>=0 && n<= 720;
}
double calculatePakg_A(int hrs)
{
if(hrs <=50)
{
return 15.00;
}
else
{
return (hrs-50) * 2.00 + 15;
}
}
double calculatePakg_B(int hrs)
{
if(hrs <=100)
{
return 20.00;
}
else
{
return (hrs-100) * 1.50 + 20.00;
}
}
double calculatePakg_C(int hrs)
{
if(hrs <=150)
{
return 25.00;
}
else
{
return (hrs-150) * 1.00 + 25.00;
}
}
Package.txt
A a B b C c e c
Hours.txt
50 51 100 101 149 251 750 722
As I'm sure you know, you can read multiple fields from a stream:
ifstream inputFile;
char a;
inputFile.open("Packages.txt");
inputFile >> a;
cout << a << endl;
inputFile >> a;
cout << a << endl;
The reason your code doesn't work is that when control returns from getPackage(), the variable inputFile is deleted, so every time you call that function, it opens the file anew and starts reading from the beginning.
One solution is to make the input stream a static variable, so that it will not be deleted, but will maintain its state from one call to the next:
char getPackage()
{
static ifstream inputFile("Packages.txt");
char a;
inputFile >> a;
return a;
}
I think the only issue here is this.
In the function getPackage()
inputFile.open("Packages.txt");
This opens the file every time you call this function
Due to this, this function is reading the first entry (only) every time.
The same issue with getHours function.
One way out is you can read all entries from the file once into a data structure, say vector and iterate through the vector in the main function.
Another way is open the file(s) in main function and introduce a loop in main that calls these functions. Every time they are called, they would return the next entry from the file. This requires passing the opened file ifstream & as an argument to functions getHours and getPackage
I'm having quite the issue trying to figure out why these code segments are printing the error message even when I have done cout statements within the block that should return true / not print that error message. Any ideas? I'm new here so please let me know if this isn't allowed. Thanks!
Use of function:
case 'a':
{
// Format: a ID credits GPA
// Adds a student with the given student ID (ID), number of
// credits (credits), and overall GPA (GPA) to the database.
// If the student is already in the database, an error
// message should be printed indicating this.
int credits = 0;
double gpa = 0;
cin >> studentID;
cin >> credits;
cin >> gpa;
// Adds the student and checks to see if the student was actually added
// or if there was an existing student with the specified ID
bool added = addStudent(studentID, credits, gpa);
if(added == false);
{
cout << "Student already exists in database, nothing changed." << endl;
// Still prints this when executed with valid
}
break;
}
Function for adding student to array:
bool addStudent (int id, int numCredits, double gpa) {
// Check to see if student exists
if (nextEntry != 0)
{
for (int x = 0; x < 7000; x++) {
Student tmp = studentRecords[x];
if (tmp.studentId == id)
{
return false;
cout << "hey" << endl;
}
}
}
// If student does not exist, add to records database
if (nextEntry != 7000)
{
studentRecords[nextEntry].studentId = id;
studentRecords[nextEntry].numCredits = numCredits;
studentRecords[nextEntry].gpa = gpa;
nextEntry++;
return true;
// confirmed I can get here
}
return false;
}
You have an extra ; after your if (added==false) statement. This will terminate the if statement and the code after will run regardless of the check.
I'm relative new to C++ and I'm sure there is probably plenty on information on here. Unfortunately, I don't seem to understand it.
I have a class called Account with variables called Number and Balance. The Member Name is given by the User through cin and represent an Account Number. I was able to dynamically create an object through cin. and give their variables a value through cin. However, I'm not able to give the variables a value or ask for the values in the class through cin.
I have been looking for hours and just cannot figure it out. Any help is appreciated. Thanks guys.
Here is my code:
class Account {
public:
int Number;
int Balance;
};
int main() {
int Nmbr;
int Bal;
cin >> Nmbr;
cin >> Bal;
Account Nmbr; // create the object
Nmbr.Number = Nmbr; // add the cin input 'Nmbr' to the variable Number - FALSE
Nmbr.Balance = Bal; // add the cin input 'Bal' to the variable Balance - FALSE
cout << Nmbr.Number << endl; // display Account.Number - FALSE
cout << Nmbr.Balance << endl; //display Account.balance - FALSE
}
Ok I think something like this is what you are after:
account.h:
class Account
{
public:
Account();
Account(int number);
int Number;
int Balance;
};
account.cpp:
#include "account.h"
Account::Account() {}
Account::Account(int number) {
this->Number = number;
}
So then in main you would do something like:
#include <iostream>
#include "account.h"
#include <vector>
const size_t MAXNUM = 5;
int main()
{
std::vector<Account*> allAccounts;
for (int accntNumber = 0; accntNumber < MAXNUM; accntNumber++) {
Account* account = new Account(accntNumber);
allAccounts.push_back(account);
}
// Then later do other stuff:
for (int accntNumber = 0; accntNumber < MAXNUM; accntNumber++) {
Account* checkAccount = allAccounts.at(accntNumber);
std::cout << "Account # = " << checkAccount->Number << std::endl;
}
return 0;
}
Edit: added an account class with a class creator based on the account number.
This is the code I have so far, it compiles and runs fine but I need help adapting it. It is a banking app that currently works for just one account.
It needs to be adapted to with two new files: bank.h and bank.cpp and, main should contain a pointer to bank and bank should contain an array of pointers to instances of account.
so the new interface would work someting like:
account> 1 12
1 is the account# and 12 is the ammount being depositted.
I really need help adapting me code to do this, I am lost on how to create the array of pointers in bank to instances of account. Any help is much appreciated.
//main.cpp file
using namespace std;
#include <iostream>
#include <stdlib.h>
#include "account.h"
//allocate new space for class pointer
account* c = new account;
//function for handling I/O
int accounting(){
string command;
cout << "account> ";
cin >> command;
//exits prompt
if (command == "quit"){
exit(0);
}
//overwrites account balance
else if (command == "init"){
cin >> c->value;
c->init();
accounting();
}
//prints balance
else if (command == "balance"){
cout << "" << c->account_balance() << endl;
accounting();
}
//deposits value
else if (command == "deposit"){
cin >> c->value;
c->deposit();
accounting();
}
//withdraws value
else if (command == "withdraw"){
cin >> c->value;
c->withdraw();
accounting();
}
//error handling
else{
cout << "Error! Invalid operator." << endl;
accounting();
}
//frees memory
delete c;
}
int main() {
accounting();
return 0;
}
//account.h header file containing class with shared variables and functions
class account{
private:
int balance;
public:
account();
~account();
int value;
int account_balance();
int deposit();
int withdraw();
int init();
};
//account.cpp implementation file
using namespace std;
#include <iostream>
#include "account.h"
account::account(){
}
account::~account(){
}
//balance overwrite function
int account::init(){
balance = value;
}
//balance function
int account::account_balance() {
return balance;
}
//deposit function
int account::deposit(){
balance += value;
}
//withdraw function
int account::withdraw(){
//error handling
if(value>balance){
cout << "Error! insufficient funds." << endl;
return 0;
}
balance -= value;
}
First of all,
//error handling
else{
cout << "Error! Invalid operator." << endl;
accounting();
}
This look ugly, you are recursively calling accounting function after every bad input. Imagine a situation where user type 1 000 000x bad inputs... you will then try to free the memory 1 000 000x times - after one successful input!
//frees memory
delete c;
The whole accounting function is designed wrong. I suppose you don't want to destroy the account after some kind of transaction, right? I think the person who withdraws 10 dollars from their 10 million dollars account which will be then destroyed, will change bank immediately :)
So a while cycle with continue could be solution
//function for handling I/O
int accounting(){
string command;
while(true) {
cout << "account> ";
cin >> command;
//exits prompt
if (command == "quit"){
break;
}
//overwrites account balance
else if (command == "init"){
cin >> c->value;
c->init();
continue;
}
//prints balance
else if (command == "balance"){
cout << "" << c->account_balance() << endl;
continue;
}
//deposits value
else if (command == "deposit"){
cin >> c->value;
c->deposit();
accounting();
}
//withdraws value
else if (command == "withdraw"){
cin >> c->value;
c->withdraw();
continue;
}
//error handling
else{
cout << "Error! Invalid operator." << endl;
continue;
}
}
Then,
int value;
is not a class member, it should be argument of methods withdraw and deposit, like this
//deposit function
void account::deposit(int value){ //int changed to void, you are not returning anything!
balance += value;
}
//withdraw function
bool account::withdraw(int value){
//error handling
if(value>balance){
cout << "Error! insufficient funds." << endl;
return false;
}
if(value<0) {
cout << "Haha, nice try!" << endl;
return false;
}
balance -= value;
return true;
}
For an array you can use the std::vector class.
std::vector<account *>MyAccounts;
MyAccounts.push_back(new account());
Then you can use it like an array accessing it normally.
MyAccounts[i]->accountFunction();
update
I don't know enough about your code, so I give just some general examples here.
In your bank class you have a member like shown above )MyAccounts. Now when ever you add a new account to your bank, you can do it with the push back function.
For example to add a new account and set the initial amount of 100 moneyitems.
MyAccounts.push_back(new account());
size_t i = MyAccounts.size();
MyAccounts[i]->setAmount(100);
You can do something like below
class Bank
{
public:
int AddAccount(Account act){ m_vecAccts.push_back(act);}
....
private:
...
std:vector<account> m_vecAccts;
}
Update:
This is just a Bank class with vector of accounts as private member variable. AddAccount is public function which can add account to vector