Calling a class array inside of a class array C++ - c++

so I have a school project where I'm trying to create a bank account. So I have an array of class customer containing the customer name etc, this customer can have multiple accounts, so I have created an array of class accounts inside of customer. My problem is, I can't call a getter function inside of the account array, I have tried using customerArray[curr_id]->accountArray[curr_acc_num]->get_balance() however I am getting an error telling my that it is unaccessable.
Here is the code, any input would be apprechiated as it is still a work in progress.
#include <iostream>.
#include <windows.h>
#include "account.h"
#include "customer.h"
using namespace std;
bool quit;
int amount;
double bal;
bool valid_pin;
customer* customerArray[200];
account* accountArray[5];
int curr_id;
int curr_acc_num;
//1st name, 2nd name, ID
customer cust1("Paul", "Smith", 2233);
//ID, Deposit, Pin
account Paul(112, 222, 6716);
//Welcome screen function
void welcome_screen() {
cout << endl << endl << endl;
cout << "\tAbertay Banking" << endl;
cout << "\t System " << endl << endl << endl;
Sleep(1800);
}
//Display account balance function
void account_balance() {
system("cls");
cout << endl << endl;
cout << "\tBank of Abertay" << endl << endl;
cout << " " << customerArray[curr_id]->get_name() << endl;
cout << " ID: " << customerArray[curr_id]->get_custid() << endl << endl;
cout << " Balance: " << char(156) << customerArray[curr_id]->accountArray[curr_acc_num]->get_balance() << endl;
//Display any outstanding loans
if (Paul.get_loan() > 0) {
cout << endl << endl;
cout << " Outstanding loan: -" << char(156) << Paul.get_loan();
Sleep(3000);
}
//User has no loan on this account
else {
Sleep(3000);
}
}
//Withdrawl function
void withdrawl() {
bal = Paul.get_balance();
system("cls");
cout << endl << endl;
cout << "\tBank of Abertay" << endl << endl;
cout << "Enter the amount you wish to withdraw: ";
cin >> amount;
//customer has sufficent funds, withdrawl accepted
if (amount <= bal + Paul.get_overdraft()) {
bal -= amount;
Paul.set_balance(bal);
system("cls");
cout << endl << endl;
cout << "\tBank of Abertay" << endl << endl; cout << "You have withdrawn: " << char(156) << amount << endl;
cout << "You now have a balance off: " << char(156) << bal << endl;
cout << "Do you wish to carry out another transaction?"; //do you wish to carry out another transaction.
Sleep(2000);
}
//customer doesn't have enough funds to carry out withdrawl
else {
char choice;
system("cls");
cout << endl << endl;
cout << "\tBank of Abertay" << endl << endl;
cout << "You have insufficient funds in your account" << endl;
}
}
//Deposit function
void deposit() {
//balance from user account
bal = Paul.get_balance();
char check;
double ln;
system("cls");
cout << endl << endl;
cout << "\tBank of Abertay" << endl << endl;
cout << "Enter the amount you wish to deposit: ";
cin >> amount;
//Option to pay off loan, if applicable
if (Paul.get_loan() > 0) {
system("cls");
cout << endl << endl;
cout << "\tBank of Abertay" << endl << endl;
cout << "Do you want to pay off your loan? (Y/N)" << endl;
cin >> check;
system("cls");
cout << "\tBank of Abertay" << endl << endl;
//User selected to pay off loan
if (check == 'y') {
//deposit paid into loan
if (amount < Paul.get_loan()) {
ln = Paul.get_loan() - amount;
Paul.set_loan(ln);
cout << "Your loan is now at: -" << char(156) << Paul.get_loan() << endl;
}
//loan is payed of, any extra money is deposited into balance
else {
ln = amount - Paul.get_loan() + Paul.get_balance();
Paul.set_loan(0);
Paul.set_balance(ln);
cout << "You have payed your loan off!" << endl;
}
}
}
//user has no loan or doesn't wish to pay off loan
else {
bal += amount;
Paul.set_balance(bal);
}
cout << "You have deposited: " << char(156) << amount << endl;
cout << "You now have a balance off: " << char(156) << bal << endl;
cout << "Would you like to select another option with this account?"; //do you wish to carry out another transaction.
Sleep(1500);
}
//Apply for overdraft
void overdraft() {
system("cls");
char choice;
cout << endl << endl;
cout << "\tTake out an overdraft of " << char(156) << "300? " << endl;
cout << "\t (Y/N)" << endl;
cin >> choice;
if (choice == 'y') {
Paul.set_overdraft(300);
}
}
//Calculating interest rates
double interest_rate(int loan) {
//Up to £3,000 rate of 11%
if (loan < 3000) {
return 1.11;
}
//From £3,000 to £7,000 rate of 9%
else if (loan > 3000 && loan < 7000) {
return 1.09;
}
//From £7,000 to £21,000 rate of 7%
else if (loan > 7000 && loan < 21000) {
return 1.07;
}
//From £21,000 over rate of 5%
else if (loan < 21) {
return 1.05;
}
}
//Loan eligibility funcition
void loan_elgibility() {
double max_loan;
double loan;
//Calculating loan eligibility
system("cls");
cout << endl << endl;
cout << "\tBank of Abertay" << endl << endl;
cout << "Caculating loan eligibility";
max_loan = (2 * Paul.get_balance());
Sleep(800);
//Loan and rates
system("cls");
cout << endl << endl;
cout << "\tBank of Abertay" << endl << endl;
cout << " You are eligible to borrow up to: " << char(156) << max_loan << endl << endl;
cout << " Interest rates are as follows" << endl << endl;
cout << " - " << char(156) << "3,000 at 11%" << endl;
cout << " " << char(156) << "3,000 - " << char(156) << "7,000 at 9%" << endl;
cout << " " << char(156) << "7,000 - " << char(156) << "21,000 at 7%" << endl;
cout << " " << char(156) << "21,000 - at 5%" << endl;
Sleep(6200);
//User input loan request
system("cls");
cout << endl << endl;
cout << " Bank of Abertay" << endl << endl;
cout << " Enter loan request: " << char(156);
cin >> loan;
//Processing loan request
system("cls");
cout << endl << endl;
cout << " Bank of Abertay" << endl << endl;
cout << " We are processing your request..." << endl;
Sleep(800);
system("cls");
//Loan has been approved, loan deposited into account
if (loan <= Paul.get_balance()) {
cout << endl << endl;
cout << " Bank of Abertay" << endl << endl;
cout << "Your loan has been approved" << endl;
bal = Paul.get_balance() + loan;
loan = interest_rate(loan) * loan;
Paul.set_balance(bal);
Paul.set_loan(loan);
Sleep(800);
}
//Loan has not been approved
else {
cout << endl << endl;
cout << " Bank of Abertay" << endl << endl;
cout << "You do not qualify for a loan of this amount";
Sleep(800);
}
}
//Quit function
void quit_screen() {
system("cls");
char choice;
cout << endl << endl;
cout << " Bank of Abertay" << endl << endl;
cout << " Do you want to quit? (Y/N) " << endl;
cout << " ";
cin >> choice;
// customer wants to quit, end while loop and program
if (choice == 'y') {
system("cls"); //clear screen
cout << endl << endl << endl;
cout << " Thanks for using," << endl;
cout << " Bank of Abertay!"<< endl;
Sleep(2000);
quit = true;
}
else {
quit = false;
}
}
//Request user pin number
bool pin_request() {
double pin;
int counter = 0;
do {
system("cls");
cout << endl << endl;
cout << "\tBank of Abertay" << endl << endl;
cout << "\tEnter pin: ";
cin >> pin;
if (pin == Paul.get_pin()) {
return true;
}
else if (counter == 3) {
cout << "You have entered an invalid pin too many times!";
Sleep(800);
return false;
}
else {
system("cls");
cout << endl << endl;
cout << " Bank of Abertay" << endl << endl;
cout << "You have entered an invalid pin" << endl;
Sleep(800);
valid_pin = false;
counter++;
}
} while (valid_pin == false && counter < 3);
}
//Adding a new customer
int counter = 0;
void add_customer(string first_nom, string second_nom, int cust_ID) {
customer* new_customer = new customer(first_nom, second_nom, cust_ID);
customerArray[counter] = new_customer;
counter++;
}
//creating new bank account
void create_account()
{
int input_custid;
double input_balance;
int input_pin;
string first_nom;
string second_nom;
int cust_ID;
char choice;
//Request new customer information
system("cls");
cout << endl << endl;
cout << "\tBank of Abertay" << endl << endl;
cout << "Enter first name: ";
cin >> first_nom;
cout << endl;
cout << "Enter surname: ";
cin >> second_nom;
cout << endl;
cout << "Customer ID: ";
cin >> cust_ID;
//create new customer class array
add_customer(first_nom, second_nom, cust_ID);
//creating new account array
system("cls");
cout << endl << endl;
cout << "\tBank of Abertay" << endl << endl;
cout << "Enter The account No. :";
cin >> input_custid;
cout << "Initial deposit in new account: ";
cin >> input_balance;
cout << "Create pin: ";
cin >> input_pin;
system("cls");
cout << " We are processing your request..." << endl;
Sleep(800);
cust1.add_account(input_custid, input_balance, input_pin);
system("cls");
cout << "Account Created.." << endl;
cout << "Thank you for joining the Bank of Abertay";
Sleep(800);
}
//find user account
bool find_account() {
int custID;
int counter;
bool found_account;
system("cls");
cout << endl << endl;
cout << " Bank of Abertay" << endl << endl;
cout << " Enter your customer ID: ";
cin >> custID;
cout << " - ";
cin >> curr_acc_num;
//not happy about this!!
for (int i = 0; i < 200; i++) {
if (customerArray[i]->get_custid() == custID) {
curr_id = i;
return true;
}
else if (i == 199) {
return false;
}
}
}
//an option to send money to another account?
// need a function that takes user back to option menu if wrong pin enter!
int main() {
//welcome screen
welcome_screen();
//while loop until player decides to quit
do {
int option_choice;
system("cls"); //clear screen, updating board every time function called
cout << endl << endl;
cout << "\tBank of Abertay" << endl << endl;
cout << "\t Menu" << endl << endl;
cout << "\t1. View Balance" << endl;
cout << "\t2. Withdraw" << endl;
cout << "\t3. Deposit" << endl;
cout << "\t4. Loan eligibility" << endl;
cout << "\t5. New account" << endl;
cout << "\t6. Overdraft" << endl;
cout << "\t7. Quit" << endl << endl;
cout << "\t\tSelect: ";
cin >> option_choice;
//ensure option screen only runs through once unless an invalid option is chosen
int valid_number_check = 0;
// do {
switch (option_choice) {
//Display account balance
case 1:
if (find_account() == true && pin_request() == true) {
account_balance();
break;
}
else {
cout << "Your request has been denied";
break;
}
//Account withdrawl
case 2:
if ( find_account() == true && pin_request() == true) {
withdrawl();
break;
}
else {
cout << "Your request has been denied";
break;
}
//Account deposit
case 3:
if (find_account() == true && pin_request() == true) {
deposit();
break;
}
else {
cout << "Your request has been denied";
break;
}
//Loan eligibility
case 4:
if (find_account() == true && pin_request() == true) {
loan_elgibility();
break;
}
else {
cout << "Your request has been denied";
break;
}
//Create new account
case 5:
create_account();
break;
//Overdraft
case 6:
if (find_account() == true && pin_request() == true) {
overdraft();
break;
}
else {
cout << "Your request has been denied";
break;
}
//Quit
case 7:
quit_screen();
break;
//Invalid number entered
default:
cout << endl << endl;
cout << " Bank of Abertay" << endl << endl;
cout << "Please enter a valid number";
Sleep(800);
break;
}
} while (quit == false);
}
// main
Account .h
#pragma once
#include <string>
#include "account.h"
using namespace std;
class customer
{
private:
int custid;
string name;
account* accountArray[5];
int counter = 0;
public:
int get_custid();
customer(string, string, int);
string get_name();
void add_account(int, double, int);
~customer();
};
Account.cpp
#include "customer.h"
#include "account.h"
#include <string>
using namespace std;
customer::customer(string first_nom, string second_nom, int cust_ID) {
counter++;
string first_name = first_nom;
string sur_name = second_nom;
//counting the number of accounts
counter++;
//identification of customer array
//custid = counter + 1000;
custid = cust_ID;
}
customer::~customer()
{
}
int customer::get_custid() {
return custid;
}
void customer::add_account(int id, double dep, int pin) {
account* new_account = new account(id, dep, pin);
accountArray[counter] = new_account;
counter++;
}
string customer::get_name() {
return name;
}
customer.h
#pragma once
class account
{
private:
double balance;
int custid;
double loan_amount;
double overdraft;
int pin;
int account_number;
public:
account(int, double, int);
~account();
//getters
double get_balance();
double get_loan();
double get_pin();
double get_overdraft();
//setters
void set_overdraft(double over);
void set_balance(double bal);
void set_loan(double loan);
};
customer.cpp
#include "account.h"
#include <iostream>
#include <windows.h>
using namespace std;
account::account(int input_custid, double input_balance, int input_pin)
{
custid = input_custid;
balance = input_balance;
pin = input_pin;
loan_amount = 0;
overdraft = 0;
}
account::~account()
{
}
double account::get_balance()
{
return balance;
}
double account::get_loan()
{
return loan_amount;
}
double account::get_pin()
{
return pin;
}
double account::get_overdraft()
{
return overdraft;
}
void account::set_balance(double bal)
{
balance = bal;
}
void account::set_loan(double loan)
{
loan_amount = loan;
}
void account::set_overdraft(double over)
{
overdraft = over;
}

Related

C++ codeblock Linux console menu

I am trying to build a menu on console on C++ with CodeBlock. Is for a course.
I would like to validate garbage enter by the user. For example, the user have to enter a number. If he enters a wrong number, no problem, the program work and continue. But if He enters a letter or some garbage, the program start on infinite loop.
I cannot use system(PAUSE) because I am programming on Linux.
I tried some code like cin.get() or do while with cin.get() but no result.
Here is my code :
#include <iostream>
using namespace std;
void showMenu()
{
cout << "---------------MENU --------------" << endl;
cout << "1- Check balance :" << endl;
cout << "2- Check deposit :" << endl;
cout << "3- Withdraw:" << endl;
cout << "4- Exit" << endl;
cout << "--------------------------------" << endl;
}
int main()
{
int option;
double balance = 500;
do
{
showMenu();
cout << "Option: ";
cin >> option;
cout << "\033[2J\033[1;1H";
switch(option)
{
case 1:
cout << "Balance is: " << balance << " $" << endl;
break;
case 2:
cout << "Deposit amount: " << endl;
double depositAmount;
cin >> depositAmount;
balance += depositAmount;
break;
case 3:
cout << "Withdraw amount: " << endl;
double withdrawAmount;
cin >> withdrawAmount;
if (withdrawAmount <= balance) {
balance -= withdrawAmount;
}
else {
cout << "Not enough money" << endl;
}
break;
default:
cout << "Your choice is invalid ";
do {
cout << '\n' << "Press the Enter key to continue.";
}while (cin.get() != '\n');
}
} while(option != 4);
return 0;
}
Do you have an idea how can I validate easily the garbage enter by the user ?
Thank you for your Help
It works with the code on default part : cin.clear and cin.ignore(). This last one is important. Thank you to user4581301
#include <iostream>
using namespace std;
void showMenu()
{
cout << "---------------MENU --------------" << endl;
cout << "1- Check balance :" << endl;
cout << "2- Check deposit :" << endl;
cout << "3- Withdraw:" << endl;
cout << "4- Exit" << endl;
cout << "--------------------------------" << endl;
}
int main()
{
int option;
double balance = 500;
do
{
showMenu();
cout << "Option: ";
cin >> option;
cout << "\033[2J\033[1;1H";
switch(option)
{
case 1:
cout << "Balance is: " << balance << " $" << endl;
break;
case 2:
cout << "Deposit amount: " << endl;
double depositAmount;
cin >> depositAmount;
balance += depositAmount;
break;
case 3:
cout << "Withdraw amount: " << endl;
double withdrawAmount;
cin >> withdrawAmount;
if (withdrawAmount <= balance) {
balance -= withdrawAmount;
}
else {
cout << "Not enough money" << endl;
}
break;
default:
cout << "\033[2J\033[1;1H"; //for clean screen with Linux
cout << "Your choice is invalid " << endl;
cin.clear();
cin.ignore();
}
} while(option != 4);
return 0;
}

different option throw an unexpected error

when I'm executing this program, it works fine just for one option, but if I try to choose an other option when executing, it will throw an error in this line:
cout << "The available quantity is: " << *(it->second.find(disp)) << endl;
here's my program:
void avail_art(void)
{
char c,con;
int quantity,disp=MAX;
bool b = true;
map<string, unordered_set<int>>m{
{"Mouse",{120,disp}},
{"Keyboard",{75,disp}},
{"Monitor",{750,disp}},
{"GPU",{1200,disp}},
{"CPU",{1000,disp}}
};
auto it = m.find("CPU");
cout << "M - for mouse." << endl;
cout << "K - for keyboard." << endl;
cout << "R - for monitor." << endl;
cout << "G - for GPU." << endl;
cout << "C - for CPU." << endl;
cout << "Q - for quit." << endl;
cout << "======================" << endl;
while (b)
{
cout << "Enter your choice: ";
cin >> c;
switch (c)
{
case 'M':
it = m.find("Mouse");
cout << "You've choosen the Mouse!" << endl;
cout << "The available quantity is: " << *(it->second.find(disp)) << endl;
l:
cout << "Enter the quantity: ";
cin >> quantity;
if (quantity > * (it->second.find(disp)))
{
cout << "Out of Stock! the Stock has only :" << *(it->second.find(disp)) <<" Piece."<< endl;
goto l;
}
cout << "Confirm? y/n: ";
cin >> con;
if (con == 'y')
{
auto its=it->second.find(disp);
it->second.insert(disp=(*its - quantity));
it->second.erase(its);
}
break;
case 'K':
it = m.find("Keyboard");
cout << "You've choosen the Keyboard!" << endl;
cout << "The available quantity is: " << *(it->second.find(disp)) << endl;
cout << "Enter the quantity: ";
cin >> quantity;
cout << "Confirm? y/n :";
cin >> con;
if (con == 'y')
{
auto its = it->second.find(disp);
it->second.insert(disp = (*its - quantity));
it->second.erase(its);
}
break;
}
}
}
can someone help me please

C++ MDC Final - Sort Names in Records Alphabetically While in Array Struct of Type Char

I was able to write a program to pass my c++ class in college except for one feature. I was unable to create a function that sorted the names inside an array of structs with name of type char alphabetically. Please advise on how to tackle this problem.
I would need a function that sorts the accountRecords array alphabetically.
#include <iostream>
#include <ctime>
#include <fstream>
#include <string>
#include <vector>
#include <string>
#include <iomanip>
using namespace std;
//Structure Initilizations
const int NAME_SIZE = 25, ADDR_SIZE = 100, CITY_SIZE = 51, STATE_SIZE = 4, DATE_SIZE = 16, CUSTOMER_ID = 10, TRANSACTION_TYPE = 16;
struct MasterRecord
{
int customerID;
char name[NAME_SIZE]; // SORT THIS FIELD ALPHABETICALLY
char address[ADDR_SIZE];
char city[ADDR_SIZE];
char state[STATE_SIZE];
char zip[STATE_SIZE];
float accountBalance;
char lastTransactionDate[15];
};
struct TransactionRecord
{
int customerID;
char transactionType;
float amount;
char transactionDate[15];
};
//File Array Initializations
vector<MasterRecord> masterRecordList(101);
vector<TransactionRecord> transRecordList(101);
//Array List Record Position
int masterRecordArrayPosition = 0;
int transactionRecordArrayPosition = 0;
//User Menu Answer Variable Initialization
int userAnswer = 0;
string recordNotFoundAnswer = "";
//Print Function Prototypes
void showMenu();
void showMasterRecord(int);
void showTransactionRecord(int);
//Main Menu Function Prototypes
void newCustomerRecord(int);
void editCustomerRecord(int);
void deleteCustomerRecord(int);
int randomComputerID();
int searchMasterRecord(int);
void saveAccountRecords();
void saveTransRecords();
void newTransactionRecord(int);
//Placeholders Variables
int customerIDsearch = 0;
int customerIDSearchArrayPosition = 0;
int userNameCharactererror = 0;
//Function Loop Counters
int accountWriteCounter = 0;
int transWriteCounter = 0;
int showRecordCounter = 0;
int showTransCounter = 0;
//System time Declaration and Conversion for [lastTransactionDate]
time_t now = time(0);
tm *ltm = localtime(&now);
string currentYearInString = to_string(1900 + ltm->tm_year);
string currentMonthInString = to_string(1 + ltm->tm_mon);
string currentDayInString = to_string(ltm->tm_mday);
string currentDateInString = currentMonthInString + "/" + currentDayInString + "/" + currentYearInString;
char dateInChar[15];
//Main Program
int main()
{
//Final conversion of time in string to char for storage
strncpy_s(dateInChar, currentDateInString.c_str(), 15);
//Open MasterRecord file and read records to arrays
fstream masterRecord("masterRecord.dat", ios::in | ios::binary);
int listCounter = 0;
if (!masterRecord) {
cout << "Unable to open the user records file, creating file database....Done!" << endl;
masterRecord.open("masterRecord.dat", ios::out | ios::binary);
}
else {
while (!masterRecord.eof()) {
masterRecord.read(reinterpret_cast<char *>(&masterRecordList[listCounter]), sizeof(masterRecordList[0]));
if (masterRecordList[listCounter].customerID != 0) {
listCounter++;
}
masterRecordArrayPosition = listCounter;
}
masterRecord.close();
}
//Open Transaction Record and read to arrays
fstream transactionRecord("transactionRecord.dat", ios::in | ios::binary);
int listCounter2 = 0;
if (!transactionRecord) {
cout << "Unable to open the transaction file, creating file database....Done!" << endl << endl;
transactionRecord.open("transactionRecord.dat", ios::out | ios::binary);
}
else {
while (!transactionRecord.eof()) {
transactionRecord.read(reinterpret_cast<char *>(&transRecordList[listCounter2]), sizeof(transRecordList[0]));
if (transRecordList[listCounter2].customerID != 0) {
listCounter2++;
}
transactionRecordArrayPosition = listCounter2;
}
transactionRecord.close();
}
//Time Declaration Used to Generate Random IDs
srand((unsigned)time(0));
//Main user Program Loop
while (userAnswer != 6) {
showMenu();
cin >> userAnswer; cout << endl;
//Menu Input Data Validation
if (cin.fail()) {
cout << "Please only enter numbers 1-6 for the corresponding menu selection." << endl;
cin.clear();
cin.ignore();
}
else {
if (userAnswer < 1 || userAnswer > 7) {
cout << "Please only enter numbers 1-6 for the corresponding menu selection." << endl;
userAnswer = 0;
}
}
//Menu Selection Switch Case
switch (userAnswer) {
case 1:
newCustomerRecord(masterRecordArrayPosition);
cout << "Record has been saved." << endl << endl;
break;
case 2:
newTransactionRecord(transactionRecordArrayPosition);
break;
case 3:
cout << "Please enter the Customer ID you would like to Delete" << endl << endl; //[Delete Customer Record] Function goes here
cin >> customerIDsearch;
customerIDSearchArrayPosition = searchMasterRecord(customerIDsearch);
if (customerIDSearchArrayPosition != 9999) {
deleteCustomerRecord(customerIDSearchArrayPosition);
}
break;
case 4:
cout << "Please enter the Customer ID you would like to edit." << endl << endl; //[Search/Edit Customer Record] Function goes here
cin >> customerIDsearch;
customerIDSearchArrayPosition = searchMasterRecord(customerIDsearch);
if (customerIDSearchArrayPosition != 9999) {
editCustomerRecord(customerIDSearchArrayPosition);
}
else {
cout << "Record was not found, would you like to add a new record? Y = Yes, N = No" << endl << endl;
cin >> recordNotFoundAnswer;
if (recordNotFoundAnswer == "Y" | recordNotFoundAnswer == "y") {
newCustomerRecord(masterRecordArrayPosition);
cout << "Record has been saved." << endl << endl;
}
else if (recordNotFoundAnswer == "N" | recordNotFoundAnswer == "n") {
userAnswer = 0;
}
}
break;
case 5:
cout << setw(212) << "Please find all customer records in the database" << endl << endl; //[Show all Records] Function goes here
cout << setw(40) << "Name:" << setw(10) << "ID:" << setw(23) << "Street Address:" <<setw(10) << "ZIP:" << setw(16) << "L.Trans Date:" << setw(11) << "Balance: " << endl;
while (showRecordCounter < 100) {
if (masterRecordList[showRecordCounter].customerID != 0) {
showMasterRecord(showRecordCounter);
}
showRecordCounter = showRecordCounter + 1;
} showRecordCounter = 0;
userAnswer = 0;
cout << endl;
break;
case 6:
cout << "Saving changes to database...Done!" << endl;
saveAccountRecords();
saveTransRecords();
cout << "Done!" << endl;
break;
case 7:
cout << "Showing all transaction Records:" << endl << endl;
while (showTransCounter < 100) {
if (transRecordList[showTransCounter].customerID != 0) {
showTransactionRecord(showTransCounter);
}
showTransCounter = showTransCounter + 1;
} showTransCounter = 0;
userAnswer = 0;
break;
}
}
return 0;
}
//Databas Management Functions
void saveAccountRecords() {
fstream masterRecord("masterRecord.dat", ios::out | ios::binary);
while (accountWriteCounter < 100) {
masterRecord.write(reinterpret_cast<char *>(&masterRecordList[accountWriteCounter]), sizeof(masterRecordList[0]));
accountWriteCounter++;
}
masterRecord.close();
}
void saveTransRecords() {
fstream transRecord("transactionRecord.dat", ios::out | ios::binary);
while (transWriteCounter < 100) {
transRecord.write(reinterpret_cast<char *>(&transRecordList[transWriteCounter]), sizeof(transRecordList[0]));
transWriteCounter++;
}
transRecord.close();
}
//Random Function
int randomComputerID() {
int randomNumber;
randomNumber = (rand() % 1000) + 10000;
return randomNumber;
}
//Program Print Functions
void showMenu() {
cout << "Welcome to your C++ company terminal! Please enter one of the options below to continue." << endl << endl;
cout << "1. New Customer Record" << endl;
cout << "2. New Transaction Record" << endl;
cout << "3. Delete Customer Record" << endl;
cout << "4. Edit Customer Record" << endl;
cout << "5. Show all Account Records in Database" << endl;
cout << "6. Exit and Save Changes to Database" << endl << endl;
cout << "Please enter the number for the correspondent action you would like to perform:" << endl;
}
void showMasterRecord(int arrayNum) {
cout << setw(40)
<< masterRecordList[arrayNum].name << setw(10) << masterRecordList[arrayNum].customerID << setw(23)
<< masterRecordList[arrayNum].address << setw(10)
<< masterRecordList[arrayNum].zip << setw(16)
<< masterRecordList[arrayNum].lastTransactionDate << setw(6) <<"$"
<< masterRecordList[arrayNum].accountBalance; cout << endl;
}
void showTransactionRecord(int arrayNum) {
cout << "Customer ID: " << transRecordList[arrayNum].customerID << endl;
cout << "Amount: $" << transRecordList[arrayNum].amount << endl;
cout << "Transaction Type: " << transRecordList[arrayNum].transactionType << endl;
cout << "Transaction Date: " << transRecordList[arrayNum].transactionDate << endl << endl;
}
//Main Menu Functions [Please insert your functions here and prototype them above].
void newCustomerRecord(int arrayNum) {
cout << "Customer ID: ";
masterRecordList[arrayNum].customerID = randomComputerID();
cout << masterRecordList[arrayNum].customerID; cout << endl;
cin.ignore();
do
{
cout << "Name: ";
cin.getline(masterRecordList[arrayNum].name, 25);
if (cin.fail()) {
cout << endl << "Please enter only characters up 25 chracters for your name." << endl;
userNameCharactererror = 1;
cin.clear();
cin.ignore(80, '\n');
}
else {
userNameCharactererror = 0;
}
} while (userNameCharactererror == 1);
cout << "Address: ";
cin.getline(masterRecordList[arrayNum].address, 100);
cout << "City: ";
cin >> masterRecordList[arrayNum].city;
cout << "State: ";
cin >> masterRecordList[arrayNum].state;
cout << "Zip Code: ";
cin >> masterRecordList[arrayNum].zip;
cout << "Opening Balance: $";
cin >> masterRecordList[arrayNum].accountBalance; cout << endl; cout << endl;
masterRecordArrayPosition = masterRecordArrayPosition + 1;
}
void editCustomerRecord(int arrayNum) {
cout << "Customer ID: ";
cout << masterRecordList[arrayNum].customerID; cout << endl;
cin.ignore();
cout << "Name: ";
cin.getline(masterRecordList[arrayNum].name, 51);
cout << "Address: ";
cin.getline(masterRecordList[arrayNum].address, 100);
cout << "City: ";
cin >> masterRecordList[arrayNum].city;
cout << "State: ";
cin >> masterRecordList[arrayNum].state;
cout << "Zip Code: ";
cin >> masterRecordList[arrayNum].zip;
cout << "Edit Balance: $";
cin >> masterRecordList[arrayNum].accountBalance; cout << endl; cout << endl;
}
void deleteCustomerRecord(int arrayNum) {
if (masterRecordList[arrayNum].accountBalance == 0)
{
masterRecordList[arrayNum].customerID = 0;
cout << "Record has been deleted" << endl << endl;
}
else {
cout << "Unable to delete record, customer accounts holds a positive balance" << endl << endl;
}
}
int searchMasterRecord(int customerID) //Search by customer name and returns array position
{
int arrayPosition = 0;
int arrayCounter = 0;
int customerIdPlaceholder = 0;
while (arrayCounter < 100) {
customerIdPlaceholder = masterRecordList[arrayCounter].customerID;
if (customerIdPlaceholder == customerID) {
cout << "Record has been found!" << endl << endl;
arrayPosition = arrayCounter;
arrayCounter = 100;
}
else {
arrayPosition = 9999;
}
arrayCounter = arrayCounter + 1;
}
return arrayPosition;
};
void newTransactionRecord(int arrayNum) {
// Request customer ID and transaction type from the user
cout << "Customer ID: ";
cin >> transRecordList[arrayNum].customerID;
cin.ignore();
cout << "Date: ";
strncpy_s(transRecordList[arrayNum].transactionDate, dateInChar, 15);
cout << transRecordList[arrayNum].transactionDate << endl;
cout << "Transaction Type [D = Deposit] [W = Withdrawal]: ";
cin >> transRecordList[arrayNum].transactionType;
cout << "Amount: $";
cin >> transRecordList[arrayNum].amount;
//Search for customer account, update balance, and assign last transaction date
customerIDSearchArrayPosition = searchMasterRecord(transRecordList[arrayNum].customerID);
if (customerIDSearchArrayPosition != 9999) {
if (transRecordList[arrayNum].transactionType == 'D') {
masterRecordList[customerIDSearchArrayPosition].accountBalance = masterRecordList[customerIDSearchArrayPosition].accountBalance + transRecordList[arrayNum].amount;
strncpy_s(masterRecordList[customerIDSearchArrayPosition].lastTransactionDate, dateInChar, 9);
cout << "Deposit Successful! " << endl << endl;
}
else if (transRecordList[arrayNum].transactionType == 'W') {
masterRecordList[customerIDSearchArrayPosition].accountBalance = masterRecordList[customerIDSearchArrayPosition].accountBalance - transRecordList[arrayNum].amount;
strncpy_s(masterRecordList[customerIDSearchArrayPosition].lastTransactionDate, dateInChar, 9);
cout << "Withdrawl Successful" << endl << endl;
}
}
else {
cout << "Customer account record was not found, transaction was not saved." << endl << endl;
}
transactionRecordArrayPosition = transactionRecordArrayPosition + 1;
}
Something along these lines:
std::sort(masterRecordList.begin(),
masterRecordList.begin() + masterRecordArrayPosition,
[](const MasterRecord& l, const MasterRecord& r) {
return strcmp(l.name, r.name) < 0;
});

Data from a static vector left unchanged when I leave the method

This is a Bank project I had in mind while learning C++ and I
have been adding to it as I learned inheritance and pointers. The
user is a bank teller who can create a new customer or process
transactions of an existing customer.
A Customer has Savings and Checking classes as private fields that inherit
from Account. The Bank class adds/gets customers from its private static vector<Customer> field.
The unexpected result is that in the 'process_transaction' method I can fetch
a customer from vector and deposit/withdrawl from it's accounts, but once I leave the method and come back to it the accounts data hasn't changed from the time I initialized them.
Need help. It's a reference to customer issue? When should I return by
reference or pointer?
Here is the code. In the driver class I have a method to create a customer
/*
* Create customer from teller input then add the Customer
* to Bank's private static vector<Customer> field.
*/
int create_customer(){
cout << "** Create New Customer **\n";
cout << "Customer Name: ";
string n = "";
cin >> n;
Customer* d = new Customer(n, gen_acct_number());
Customer c(*d);
// get opening balances
double open_ck = 0;
double open_sv = 0;
cout << "Opening Balance For Checking: ";
cin >> open_ck;
cout << "Opening Balance For Savings: ";
cin >> open_sv;
cout << "\n";
// create and set accounts
Checking ck(open_ck);
Savings sv(open_sv);
c.set_checking(ck);
c.set_savings(sv);
// add customer to bank
Bank b;
b.add_customer(c);
cout << "New Customer: " << c.get_name() << endl;
cout << "Account Number: " << c.get_acct_number() << endl;
cout << "\n";
return 0;
}
I have another method in the driver class to process a customer. Once I
leave this method a customer's accounts are unchanged, but works otherwise.
/*
* Fetch customer by account number from Bank's private static
* vector<Customer> and perform transactions on Customer's accounts
* until teller has finished processing the customer.
*/
int process_customer(){
cout << "** Process Transaction **\n";
cout << "Account Number: ";
int acctNum = 0;
cin >> acctNum;
cout << "\n";
// get customer
Bank b;
Customer c = b.get_customer(acctNum);
//if(c* == NULL){
// cout << "Error: Customer Not Found.\n";
// return 0;
//}
bool flag = true;
while(flag){
cout << c.get_name() << " #" << c.get_acct_number() << ": ";
cout << "Select a transaction.\n";
cout << "1. Withdrawl\n";
cout << "2. Deposit\n";
cout << "3. Check Balance\n";
cout << "4. Quit\n";
cout << "> ";
int choice = 0;
cin >> choice;
cout << "\n";
double amt = 0;
int which = 0;
switch(choice){
case 1:{ // WITHDRAWL
cout << "Withdrawl From: \n";
cout << "1. Checking \n2. Savings \n";
cout << "> ";
cin >> which;
cout << "\n";
cout << "Amount: ";
cin >> amt;
cout << "\n";
if(which == 1){
cout << "Old Balance: " << c.get_checking().get_balance() << endl;
c.get_checking().withdrawl(amt);
cout << "New Balance: " << c.get_checking().get_balance() << endl;
cout << "\n";
}else if (which == 2){
cout << "Old Balance: " << c.get_savings().get_balance() << endl;
c.get_savings().withdrawl(amt);
cout << "New Balance: " << c.get_savings().get_balance() << endl;
cout << "\n";
}else{
break;
}
break;
}
case 2:{ // DEPOSIT
cout << "Deposit Into: \n";
cout << "1. Checking \n2. Savings \n";
cout << "> ";
cin >> which;
cout << "\n";
cout << "Amount: ";
cin >> amt;
cout << "\n";
if(which == 1){
cout << "Old Balance: " << c.get_checking().get_balance() << endl;
c.get_checking().deposit(amt);
cout << "New Balance: " << c.get_checking().get_balance() << endl;
cout << "\n";
}else if (which == 2){
cout << "Old Balance: " << c.get_savings().get_balance() << endl;
c.get_savings().deposit(amt);
cout << "New Balance: " << c.get_savings().get_balance() << endl;
cout << "\n";
}else{
break;
}
break;
}
case 3:{ // CHECK BALANCE
cout << "Checking " << c.get_checking().get_balance() << endl;
cout << "Savings " << c.get_savings().get_balance() << endl;
cout << "\n";
break;
}
default:{ // EXIT
flag = false;
break;
}
}
}
return 0;
}
The Bank class.
Bank::Bank(){}
Customer& Bank::get_customer(int acct_number) {
for(unsigned i = 0; i < cus.size(); i++){
if(cus[i].get_acct_number() == acct_number){
return cus[i];
}
}
return cus[0];
}
void Bank::add_customer(Customer c){
cus.push_back(c);
}
/* Disabled. I want to pass an account to these methods.
*
* void Bank::deposit(double amt, Account& a){
* a.deposit(amt);
* }
* void Bank::withdrawl(double amt, Account& a){
* a.withdrawl(amt);
* }
* double Bank::check_balance( Account& a){
* return a.get_balance();
* }
*/
vector<Customer> Bank::cus;
Bank.h
#ifndef BANK_H_
#define BANK_H_
#include "../include/Customer.h"
#include <string>
#include <vector>
using namespace std;
class Bank{
public:
Bank();
Customer& get_customer(int acct_number);
void add_customer(Customer c);
void deposit(double amt, Account& a);
void withdrawl(double amt, Account& a);
double check_balance( Account& a);
private:
static vector<Customer> cus;
};
#endif /* BANK_H_ */
It does indeed appear to be a reference issue. In your process_customer function, change:
// get customer
Bank b;
Customer c = b.get_customer(acctNum);
to:
// get customer
Bank b;
Customer& c = b.get_customer(acctNum);
Without this change, you're making a copy of the customer and then modify this copy, instead of modifying the original customer.

Why Do I have an '=' sign output and 2 smiley faces instead of the correct output? C++

this is an update to show chages, details below.
here is a link to snap shot of output
https://dl.dropboxusercontent.com/u/34875891/wrongoutput.PNG
#include <iostream>
#include <iomanip>
#include <string>
#include <cstring>
using namespace std;
//create HotelRoom class
class HotelRoom
{
private:
char* ptr_guest;
char room_number[3];
int room_capacity;
int occupancy_status;
double daily_rate;
public:
HotelRoom(char roomNumber[], int roomCapacity, double roomRate, char* ptr_name, int occupancyStatus);
~HotelRoom();
void Display_Number();
void Display_Guest();
int Get_Capacity();
int Get_Status();
double Get_Rate();
int Change_Status(int);
double Change_Rate(double);
};
HotelRoom::HotelRoom(char roomNumber[], int roomCapacity, double roomRate, char* ptr_name, int occupancyStatus)
{
strcpy(room_number, roomNumber);
room_capacity = roomCapacity;
daily_rate = roomRate;
ptr_guest = new char[strlen(ptr_name) + 1];
strcpy(ptr_guest, ptr_name);
occupancy_status = occupancyStatus;
}
HotelRoom::~HotelRoom()
{
cout << endl;
cout << "Destructor Executed";
cout << endl;
delete [] ptr_guest;
}
void HotelRoom::Display_Guest()
{
char* temp = ptr_guest;
while(*temp != '\0')
cout << *temp++;
}
void HotelRoom::Display_Number()
{
cout << room_number;
}
int HotelRoom::Get_Capacity()
{
return room_capacity;
}
int HotelRoom::Get_Status()
{
return occupancy_status;
}
double HotelRoom::Get_Rate()
{
return daily_rate;
}
int HotelRoom::Change_Status(int roomStatus)
{
if(roomStatus <= room_capacity )
{
occupancy_status = roomStatus;
return occupancy_status;
}
else
occupancy_status = -1;
}
double HotelRoom::Change_Rate(double newRate)
{
daily_rate = newRate;
return daily_rate;
}
int main()
{
cout << setprecision(2)
<< setiosflags(ios::fixed)
<< setiosflags(ios::showpoint);
//Declare variables to hold data
char roomNumber[3] = {'1','3','\0'};
char guestName[20];
double roomRate = 89.00;
int roomCapacity = 4;
int occupancyStatus = 0;
int status;
int checkOut;
int newCustomer;
//Ask for user input
cout << "What is the guest's name: ";
cin.getline(guestName, 20);
cout << endl;
cout << "How many guests will be staying in the room: ";
cin >> status;
HotelRoom HotelRoom1(roomNumber, roomCapacity, roomRate, guestName, status);
//Display Rooom information
cout << endl;
cout << endl;
if(HotelRoom1.Change_Status(status))
{
cout << endl;
cout << "Guest's Name: ";
HotelRoom1.Display_Guest();
cout << endl;
cout << endl;
cout << "The capacity of this room is " << HotelRoom1.Get_Capacity() << endl;
cout << endl;
cout << "There are " << HotelRoom1.Get_Status() << " guests staying in the room";
}
cout << endl;
cout << endl;
cout << "Your room number is " << HotelRoom1.Display_Number();
cout << endl;
cout << endl;
cout << "The rate for this room is " << HotelRoom1.Get_Rate();
cout << endl;
cout << endl;
//chech this guest out?
cout << "Check this guest out? ('1 = yes' '0' = no) ";
cin >> checkOut;
switch(checkOut)
{
case 1:
HotelRoom1.Change_Status(0);
for(int i = 0; i < 3; ++i )
{
cout << endl;
}
cout << "You have checked out of room number " << HotelRoom1.Display_Number();
cout << endl;
cout << endl;
cout << "The capacity of this room is " << HotelRoom1.Get_Capacity();
cout << endl;
cout << endl;
cout << "There are currently " << HotelRoom1.Get_Status() << " occupants";
cout << endl;
cout << endl;
cout << "The rate of this room was " << HotelRoom1.Get_Rate();
break;
}
//check in new guest?
cout << endl;
cout << endl;
cout << "Check in new guest? ('1 = yes' '0' = no) ";
cin >> newCustomer;
for(int i = 0; i < 3; ++i )
{
cout << endl;
}
switch (newCustomer)
{
case 1:
HotelRoom HotelRoom2(roomNumber, roomCapacity, roomRate, guestName, status);
HotelRoom1.Change_Rate(175.00); //Change rate of room
cout << endl;
cout << "What is the guest's name: ";
cin.getline(guestName, 20);
cout << endl;
cout << "How many guests will be staying in the room: ";
cin >> status;
cout << endl;
cout << endl;
//Display new guest information
if(HotelRoom1.Change_Status(status))
{
cout << endl;
cout << endl;
cout << "The capacity of this room is " << HotelRoom1.Get_Capacity() << endl;
cout << endl;
cout << "There are " << HotelRoom1.Get_Status() << " guests staying in the room";
}
cout << endl;
cout << endl;
cout << "Your room number is " << HotelRoom1.Display_Number();
cout << endl;
cout << endl;
cout << "The rate for this room is " << HotelRoom1.Get_Rate();
cout << endl;
cout << endl;
break;
}
cout << endl;
system("PAUSE");
return 0;
}
this is an update to show chages, details below.
here is a link to snap shot of output
https://dl.dropboxusercontent.com/u/34875891/wrongoutput.PNG
char HotelRoom::Display_Guest()
{
cout << ptr_guest;
}
string HotelRoom::Display_Number()
{
cout << room_number;
}
int HotelRoom::Change_Status(int roomStatus)
{
if(roomStatus <= room_capacity )
{
occupancy_status = roomStatus;
return occupancy_status;
}
else
occupancy_status = -1;
}
These functions claim to be returning values. The first two are not, the last is not under certain conditons. Calling the first two is undefined behavior. Calling Change_Status with roomStatus > room_capacity is also undefined behavior.
There may be other problems with the code, but the elephant in the room is the undefined behavior. Any other debugging while you have undefined behavior is theoretically a waste of time.