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}
};
Related
asking desire number to become the for loop(how many employee if input is 4 then 4 loop if 3 3 loops), salary formula not working, if else statement for string name to not accept number and vice versa integer to not accept letters. another one of my problem is how can I name the loop for example the question is name hours and rate then the cout should do 1. name hours rate, 2.name hours rate 3.name hours rate... the code is working.. just need some imporvements.
#include <iostream>
#include <cstdlib>
using namespace std;
void displayRules()
{
cout<<"====================="<<endl;
cout<<" EMPLOYEE-SALARY "<<endl;
cout<<"====================="<<endl;
cout<<" "<<endl;
}
int main()
{
char ans;
do
{
system("cls");
displayRules();
struct Employee
{
string name;
double hours;
double rate;
double salary;
Employee *next;
Employee *prev;
};
Employee *head;
head=NULL;
Employee *newEmployee;
Employee *EmpPointer;
Employee *nextEmpPointer;
Employee *prevEmpPointer;
string inpname;
int inpN;
double inphours;
double inprate;
double salary;
salary = (inprate*inphours);
for(int ctr=0; ctr<3; ctr++)
{
cout<<endl;
cout<<"Enter Name: \t\t";
cin>> inpname;
cout<<"Enter # Hours Worked: \t";
cin>> inphours;
if (inphours<0)
{
cout << "Invalid Input! Program Stopped. ";
return 0;
}
cout<<"Enter Rate per Hour: \t";
cin>> inprate;
if (inprate<0)
{
cout << "Invalid Input! Program Stopped. ";
return 0;
}
newEmployee = new Employee;
newEmployee->name=inpname;
newEmployee->hours=inphours;
newEmployee->rate=inprate;
newEmployee->next=NULL;
if (head==NULL)
head=newEmployee;
else
{
EmpPointer=head;
while (EmpPointer->next)
EmpPointer=EmpPointer->next;
EmpPointer->next=newEmployee;
}
}
cout<<endl;
Employee *displayPointer;
displayPointer=head;
system("cls");
cout<<"------------------------------------------------------------"<<endl;
cout<<" =Summary of PAYROLL= "<<endl;
cout<<"------------------------------------------------------------"<<endl;\
cout<<"Employee Name\t"<<"# Hours Worked\t"<<"Rate/Hour\t"<<"Salary\t"<<endl;
while (displayPointer)
{
cout<<displayPointer->name<<"\t\t";
cout<<displayPointer->hours<<"\t\t";
cout<<displayPointer->rate<<"\t\t";
cout<<displayPointer->salary<<endl;
displayPointer=displayPointer->next;
}
cout<<"------------------------------------------------------------"<<endl;
cout<<endl;
cout << "Would you like to run the program again? (Y/N) ";
cin>>ans;
}
while (ans == 'y' or ans == 'Y');
return 0;
}
Note: The salary wasn't being calculated so I fix that.
I broke your code into small functions in which each function only does one thing and one thing only (Single Responsibility Principle).
Also, I introduce function templates that allows you to reuse a function when you provide the type.
Finally, the code is missing a clean up of pointers to prevent memory leaks. Each time you use the keyword new to obtain a pointer to memory, you need later to check if the pointer contains null and if doesn't then use the keyword delete to free that memory, else you end with memory leaks in your code. Therefore, I leave you with the task to write the function that should iterate your employee list and free the memory to prevent memory leaks.
I hope this is useful.
#include <iostream>
#include <cstdlib>
using namespace std;
struct Employee {
string name;
double hours;
double rate;
double salary;
Employee *next;
Employee *prev;
};
void displayRules() {
cout<<"====================="<<endl;
cout<<" EMPLOYEE-SALARY "<<endl;
cout<<"====================="<<endl;
cout<<" "<<endl;
}
// Here we create a function template to make this code more reusable
template <typename T>
T consoleInput(const std::string& prompt) {
T value;
std::cout << prompt;
std::cin >> value;
return value;
}
// Lets create our own assert to exit the app.
void assertGreaterEqualThanZero(const double value, const std::string& prompt){
if (value < 0) {
cout << prompt;
exit(1);
}
}
// Small functions that do one thing only makes coding easy to debug
Employee* createEmployee(string name, int hours, int rate) {
Employee *newEmployee = new Employee;
newEmployee->name=name;
newEmployee->hours=hours;
newEmployee->rate=rate;
newEmployee->salary = (rate * hours);
newEmployee->next=NULL;
// You need to set and maintain ->prev
// if you are thinking on using a double linked list
// else remove it from the structure since is unused.
return newEmployee;
}
// This is a helper function to add new employees to a list
Employee* addToEmployeeList(Employee* list, Employee* newEmployee){
if (list==NULL) {
list = newEmployee;
} else {
Employee *EmpPointer = list;
while (EmpPointer->next)
EmpPointer=EmpPointer->next;
EmpPointer->next=newEmployee;
}
return list;
}
// The only purpose of this function is to print the list provided
void printEmployeList(Employee* employeeList){
Employee *currentEmployee = employeeList;
system("cls");
cout<<"------------------------------------------------------------"<<endl;
cout<<" =Summary of PAYROLL= "<<endl;
cout<<"------------------------------------------------------------"<<endl;
while (currentEmployee){
cout<<"Employee Name\t"<<"# Hours Worked\t"<<"Rate/Hour\t"<<"Salary\t"<<endl;
cout<<currentEmployee->name<<"\t\t";
cout<<currentEmployee->hours<<"\t\t";
cout<<currentEmployee->rate<<"\t\t";
cout<<currentEmployee->salary<<endl;
cout<<"------------------------------------------------------------"<<endl;
currentEmployee=currentEmployee->next;
}
}
// I leave you with this piece that is missing.
// TODO: create function that delete each employee in the list,
// then deletes the list in order to prevent memory leaks
int main() {
char ans;
do {
system("cls");
displayRules();
Employee *employeeList;
employeeList=NULL;
for(int ctr=0; ctr<3; ++ctr) {
// Lets declare and instantiate when we need it.
string name = consoleInput<string>("Enter Name: \t\t");
// No need to use inp (as inphours) in front of your variables
// It makes it harder to read. Just put hours as a name.
double hours = consoleInput<double>("Enter # Hours Worked: \t");
assertGreaterEqualThanZero(hours, "Invalid Input! Program Stopped.");
double rate = consoleInput<double>("Enter Rate per Hour: \t");
assertGreaterEqualThanZero(rate, "Invalid Input! Program Stopped. ");
Employee *newEmployee = createEmployee(name, hours, rate);
employeeList = addToEmployeeList(employeeList, newEmployee);
}
cout << endl;
printEmployeList(employeeList);
cout << "Would you like to run the program again? (Y/N) ";
cin>>ans;
} while (ans == 'y' or ans == 'Y');
return 0;
}
I want to design an account management system.I have an account class for storing the details of each account, a withdrawal class for storing the information regarding the money withdrawn from a particular account and an account list class with an array of accounts and member function add_acc,search_acc that searches for a particular account and show_acc that displays information of all the accounts. But before adding an account, I want to check if the account no. to be added, already exists or not. If it exists then an error message is displayed else the new account is added.But the show_acc function is not functioning, everytime it is called, it prints some garbage value.
#include <iostream>
#include <stdlib.h>
using namespace std;
#define MAX 100
void Withdrawal(class Account_list &a);
class Account
{
long long int acc_no;
long double balance;
public :
void get_data(long long int acc,long double b=0)
{
acc=acc_no;
b=balance;
}
void show_data()
{
cout<<"Account no. : "<<acc_no<<endl;
cout<<"Balance : "<<balance<<endl;
}
long long int get_acc_no()
{
return acc_no;
}
long double get_balance()
{
return balance;
}
void update(long double b)
{
balance=balance-b;
}
friend class Account_list;
};
class Account_list
{
static int count;
Account A[MAX];
public:
void add_acc();
void show_acc();
void search_acc(long long int);
friend void Withdrawal(Account_list &a);
};
int Account_list::count=0;
void Account_list::add_acc()
{
long long int acc;
long double b;
cout<<"Enter account number : ";
cin>>acc;
cout<<"Enter balance : ";
cin>>b;
for (int i = 0; i <= count; i++)
{
if (A[i].get_acc_no() == acc)
{
cout << "\nAccount already exists enter a unique account number\n";
return;
}
}
A[count].get_data(acc, b);
count++;
}
void Account_list::search_acc(long long int ac)
{
for(int i=0;i<count;i++)
{
if(A[i].get_acc_no()==ac)
{
A[i].show_data();
return;
}
}
cout<<"Account no. not found please enter a valid account no.";
}
void Account_list::show_acc()
{
for(int i=0;i<count;i++)
{
A[i].show_data();
cout<<endl<<endl;
}
}
void Withdrawal(Account_list &a)
{
long long int acc;
long double amount;
cout<<"Enter the account no. : ";
cin>>acc;
cout<<"Enter the amount to be withdrawn : ";
cin>>amount;
for(int i=0;i<a.count;i++)
{
if(a.A[i].get_acc_no()==acc && a.A[i].get_balance()>amount)
{
a.A[i].update(amount);
cout<<"Amount withdrawn successfully\n";
return;
}
}
cout<<"Account no. not found or invalid withdrawal amount entered";
}
int main()
{
Account_list A;
char ch='Y';
long long int acc;
int i;
while(ch)
{
cout<<"1. Add account"<<"\n"<<"2. Find account"<<"\n"<<"3. Withdraw amount"<<"\n"<<"4. Display information"<<"\n";
cout<<"Enter your choice : ";
cin>>i;
switch(i)
{
case 1: A.add_acc();
break;
case 2: cout<<"Enter the account no. to be searched : ";
cin>>acc;
A.search_acc(acc);
break;
case 3: Withdrawal(A);
break;
case 4: A.show_acc();
break;
default:cout<<"Enter a valid choice";
}
cout<<"Do you wish to continue?"<<" : ";
cin>>ch;
if(ch=='Y' || ch=='y')
{
cout<<endl;
continue;
}
else
break;
}
}
The problem with my output -:
In the first run I entered the account no. as 123, int the second run I enter the acc. no. as 345 and when in the third run again I entered the acc. no. as 345, the error message was not displayed.
I am learning c++ and I can't wrap my head around this problem. I have created a class object which hold information of a vehicle. And the class name is vehicle. Here is the class:
class vehicle {
private:
string vehicleNumber;
int vehicleType;
public:
//Default Constructor
vehicle();
//Overload Constructor - #params<vehicleNumber, vehicleType>
vehicle(string vehicleNo, int type){
vehicleNumber = vehicleNo;
vehicleType = type;
}
//Some stuff to test
string getNo(){
return vehicleNumber;
}
int getType(){
return vehicleType;
}
};
And now in my main I have a void method which then takes in user input and puts the object in a vector. So in my main:
//Ref
void storeVehicle(vector<vehicle>&);
void storeVehicle(vector<vehicle>& createNewVehicle){
string number;
int type;
cout << "Enter Vehicle Number: ";
cin >> number;
cout << "Enter the vehicle type: ";
cin >> type;
vehicle newV(number, type);
createNewVehicle.push_back(newV);
cout << endl;
}
//
Now here is the problem I am facing. Inside of my main method, I am creating the object. And this works perfectly find except if I call the main method again, it initializes the object again and I loose my previous data. I am not sure how to tackle this.
Here is the main method:
int main(){
vector<vehicle> newVehicle;
storeVehicle(newVehicle);
return main();
}
So here I am returning main() again so that it reruns. But when it does, i loose my previous vector which held the data. Now how can I keep the data and keep calling the storeVehicle method?
Edit
I also have a switch case which I am using to determine what the user chooses as an option. It may be to display the vehicle information or it maybe to add a new vehicle. In this case too, how can I add the vehicle without loosing previous data. Here is my switch which is inside another method:
void mainMenu(){
int option;
cin >> option;
switch(option){
case 1: {
vector<vehicle> newVehicle;
storeVehicle(newVehicle);
break;
}
default:
cout << "Wrong option";
}
}
So now in my main method, I am simply calling this switch method. Either way, I loose the data yes?
EDIT
I don't understand why people keep downvoting. Aren't we all here to learn? And yet I get a downvote. Sooner or later, stackoverflow decides to block me from asking questions.
Main isn't intended to be used like that, it's just an entry point for your application.
For what you're looking to do, you would be interested in looping. This way a certain section of your code can be ran repeatedly until a condition is met.
int main(){
vector<vehicle> newVehicle;
while(true)
{
storeVehicle(newVehicle);
}
return 0;
}
Take a look at how different loop types work. https://www.tutorialspoint.com/cplusplus/cpp_loop_types.htm
Also, the one in my example is an infinite loop, since the condition is always true.
EDIT The question was changed.
The problem is that each time you call the mainMenu function that the vector is recreated. Create the vector in your Main function and then pass it by ref into the mainMenu function, so that it can then be passed into your storeVehicle function.
int main()
{
vector<vehicle> newVehicle;
while (true)
{
mainMenu(newVehicle);
}
return 0;
}
void mainMenu(vector<vehicle>& createNewVehicle) {
int option;
cin >> option;
switch (option) {
case 1: {
storeVehicle(createNewVehicle);
break;
}
default:
cout << "Wrong option";
}
}
You'd have to add a header for this function to work.
#include <limits>
void storeVehicle(vector<vehicle>& createNewVehicle) {
string number;
int type;
cout << "Enter Vehicle Number: ";
cin >> number;
cout << "Enter the vehicle type: ";
cin >> type;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
vehicle newV(number, type);
createNewVehicle.push_back(newV);
cout << endl;
}
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.
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.