Assign name to seat and display in array - c++

I'm having a problem assigning users to an array and then displaying the array. Typical 'flight seat-assign' program. Any help would be fantastic, as I am seriously stuck.
I haven't been getting any errors when compiling so I'm assuming I'm not too far off? code as follows.
Note, classes in separate header files.
// Flight Class - Scotia 2
// Contains information on seating (array), space available and return to menu option.
#include <iostream>
#include <string>
#include "booking.h"
using namespace std;
class Flight
{
public:
public:
struct Seat
{
int Available;
string fullName;
};// End of struct
// Structure for seat plan (24 spaces available)
struct Seat seatArray[4][6];
void seatPlan()
{ //------
cout << "Scotia Airlines Seating Plan\n";
cout << "------------------------\n";
cout << " 1D 2D 3D 4D 5D 6D\n";
cout << " 1C 2C 3C 4C 5C 6C\n";
cout << " \n";
cout << " 1B 2B 3B 4B 5B 6B\n";
cout << " 1A 2A 3A 4A 5A 6A\n";
cout << "------------------------\n\n\n";
//------
for (int i=0;i<4;i++)
{
for (int j=0;j<6;j++)
{
if (seatArray[i][j].Available == 0)
cout << seatArray[i][j].fullName << "=" << i+1;
else
cout << "Seating Plan is unavailable";
break;
}
}// End of for loop
}// End of seatPlan function
};// End of Flight class
Here is my booking class also, as I'm sure it'll help identify a problem...
//Booking class - Scotia Airlines
//This class will reserve a seat for passenger
#include <iostream>
#include <string>
using namespace std;
class Booking{
public:
struct Seat
{
int Available;
string fullName;
};// End of struct
// Structure for seat plan (24 spaces available)
struct Seat seatArray[4][6];
//variables for taking in customer details, calculating ticket cost (inc discounts) and adding details to system
public:
string fName, sName, busName, fullName;
int age, livesAt;
float discount, tickPrice, tCost;
void addBooking()
{
cout << "\tBooking Menu \n\n";
cout << "Please select ticket type: \n";
cout << "1- Business \n";
cout << "2- Western Isles \n";
cout << "3- Ordinary \n";
cin >> livesAt;
// This will be used to calc total cost for each passenger dependant on ticket type
if(livesAt == 1)
{
discount = 0.75;
cout << "Please enter your business name\n";
cin >> busName;
}
else if (livesAt == 2)
{
discount = 0.90;
}
else
{
discount = 1.0;
};
// Calculation - Standard ticket price is 60 Beans
tickPrice = 60.0;
tCost = (tickPrice * discount);
bool booked = false;
for(int i = 0; i < 4 && !booked; i++)
{
for(int j = 0; j < 6 && !booked; j++)
{
if(seatArray[i][j].Available == 1)
{
cout << "Please enter your first name \n";
cin >> fName;
cout << "Please enter your second name \n";
cin >> sName;
fullName == fName + " " + sName;
seatArray[i][j].fullName = fullName;
booked = true;
// Message on screen for customer displaying cost of flight
cout << "*******************************\n";
cout << "\tBooking for " << fName + " " + sName << " confirmed.\n";
cout << "\tTotal cost = " << tCost << " GBP.\n";
}//end of if
}//end of for2
}//end of for1
}// End of addBooking function
};// End of Booking class
Any help would be greatly appreciated!

Here are some errors I have spotted:
First of all you never mark a seat as not available. Add this to your add booing function.
Second the else in the second for in seatPlan should be in the else I believe.
You don't need a semi-column after an else statement(in the else when setting discount to 1.0)
As you never mention what are the errors you are getting this is as good as I can get. Hope this answer helps.

Related

Unable to access or display the returned "string"

Currently, I am working on a small project, called "Blood Donation". I used classes and Inheritance concepts there.
And When the new "blood donor" comes, I take its information, create the new object and store the address of the object into a "vector of pointers". But when I try to access the name of a person, I didn't get anything, I can access the other information...
Tired of finding, where is bug.....
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
#include <unistd.h>
using namespace std;
int intCheck(string str){
for(int i=0;i<str.length();i++){
if (!(str[i] >= 48 && str[i] <= 57) ) return 0;
}
return stoi(str);
}
long long int longCheck(string str){
for(int i=0;i<str.length();i++){
if (!(str[i] >= 48 && str[i] <= 57) ) return 0;
}
return stoll(str);
}
class bloodBank{
private:
// ORDER : A+ B+ AB+ O+ A- B- AB- O-
static int totalBlood;
static int bloodGroupsRecords[8];
static int maleDonars;
static int femaleDonars;
static int totalDonars;
public:
static string bloodGroups[8];
static void display_totalBlood(){
cout << "\n Total Blood In The Blood Bank :: " << totalBlood << " ML " << "( " << totalBlood/(float)1000 << " ) Ltr.";
}
static void display_gender_donars(){
cout << "\n Male Donars : " << maleDonars ;
cout << "\n Female Donars : " << femaleDonars ;
}
static void display_group_donars(){
for (int i=0;i<8;i++){
cout << setw(5) << bloodGroups[i];
cout << " : " << bloodGroupsRecords[i];
}
}
static void increaseMD(){
maleDonars++;
}
static void increaseFD(){
femaleDonars++;
}
static void increaseTB(int blood){
totalBlood += blood;
}
static void addBloodToCategory(int bGroup,int bAmount){
bloodGroupsRecords[bGroup] += bAmount;
}
};
int bloodBank :: totalBlood=0;
int bloodBank :: bloodGroupsRecords[8] = {0};
int bloodBank :: maleDonars=0;
int bloodBank :: femaleDonars=0;
int bloodBank :: totalDonars = maleDonars + femaleDonars;
string bloodBank :: bloodGroups[8] = {"A+","B+","AB+","O+","A-","B-","AB-","O-"};
class donate:public bloodBank{
private:
string name;
string village;
int bloodGroup;
int gender;
long long int phone;
int age;
int amount;
public:
void set_name(){
cout << "Enter Your Name : ";
getline(cin,name);
}
string get_name(){ cout << "Hello From get_name" ; return name;}
void set_village(){
cout << "Enter Your Village : ";
getline(cin,village);
}
string get_village(){ return village;}
int set_age(){
string s_age;
cout << "Enter Your Age : ";
getline(cin,s_age);
age = intCheck(s_age);
if (!(age >= 18 && age <=65)) { cout << "Enter The Age Properly & Age Must B/W 18 - 65 \n";set_age();}
return 1;
}
int get_age(){ return age;}
int set_phone(){
string s_phone;
cout << "Enter Your Phone : ";
getline(cin,s_phone);
phone = longCheck(s_phone);
if ((!phone) || (s_phone.length() > 12 || s_phone.length() < 6)) { cout << "Enter Your Phone Number Correctly \n";set_phone();}
return 1;
}
long long int get_phone(){ return phone;}
int set_bloodGroup(){
cout << "Choose Your Blood Group : \n";
cout << "1) A+ 2) B+ 3) AB+ 4) O+ \n";
cout << "5) A- 6) B- 7) AB- 8) O- \n";
string s_bg;
getline(cin,s_bg);
bloodGroup = intCheck(s_bg);
if(!((bloodGroup >= 1) && (bloodGroup <=8))){ cout << "Please Choose The Correct Blood Group \n"; set_bloodGroup();}
return 1;
}
int get_bloodGroup(){ return bloodGroup;}
int set_amount(){
string s_amount;
cout << "Enter Amount To Donate(ml) : ";
getline(cin,s_amount);
amount = intCheck(s_amount);
if (!(amount >= 100 && amount <= 500)){ cout << "Minimum Limit : 100 ML & Maximum Limit : 500 ML \n"; set_amount();}
return 1;
}
int get_amount(){ return amount;}
int set_gender(){
string s_gender;
cout << "Select Your Gender : \n1) Male \n2)Female \n";
getline(cin,s_gender);
gender = intCheck(s_gender);
if ((gender == -1) || (gender > 2) || (gender < 1)) { cout << "Please Select A Proper Number 1 or 2 \n";set_gender();}
else{
(gender == 1 )? gender = 1: gender = 2;
}
return 1;
}
int get_gender(){ return gender; }
void updateData(){
get_gender() == 1 ? increaseMD() : increaseFD();
increaseTB(get_amount());
addBloodToCategory(get_bloodGroup(),get_amount());
}
};
// --- BloodBank Database ---
vector<donate *> blood_bank_database;
// --- Donars Info ---
void donarsList(){
vector<donate *> :: iterator it = blood_bank_database.begin();
cout <<"normal";
cout << blood_bank_database[0]->get_gender();
cout << blood_bank_database[0]->get_name();
while(it != blood_bank_database.end()){
cout << "Name Of Donar : " << (*it)->get_name() << "Amount Of Blood Donated : " << (*it)->get_amount() ;
it++;
}
}
void menu(){
cout << "===== WELCOME TO BLOOD DONATION CAMP ====\n\n";
cout << "Use The Follwing Commands : \n";
cout << "1) Donate The Blood \n";
cout << "2) List Of Blood Donars \n";
cout << "3) Amount Of Blood Donated \n";
cout << "4) About Us \n";
cout << "5) EXIT \n\n";
}
void createDonar(){
donate d1;
d1.set_name();
d1.set_village();
d1.set_gender();
d1.set_age();
d1.set_phone();
d1.set_bloodGroup();
d1.set_amount();
d1.updateData();
blood_bank_database.push_back(&d1);
cout << "-- Thanks For Donating :) --\n";
}
void bloodDonated(){
cout << "------------------------------------\n";
bloodBank::display_totalBlood() ;
bloodBank::display_gender_donars() ;
bloodBank::display_group_donars() ;
cout << "\n------------------------------------\n";
}
void aboutUs(){
cout << "-----------------------------------------------------\n";
cout << "\n _-_-_ | OPEN-EYES BLOOD CAMP | _-_-_\n";
cout << "\n ! Donate Blood, Save Life ! \n";
cout << "\n\n-- Near Grand Park, NewWay Street, CALIFORNIA --\n\n";
cout << "-----------------------------------------------------\n";
}
int main(){
createDonar();
// donarsList();
bloodDonated();
auto it = blood_bank_database.begin();
cout << (*it)->get_gender();
cout << (*it)->get_name();
return 0;
}
void createDonar(){
donate d1;
The d1 object is declared in automatic scope in this function. This means that d1 gets destroyed when this function returns. It will be gone. It will be no more. It will cease to exist. It will become an ex-object. When you declare non-static variables and objects in a function that's what happens to them when the function returns, that's how C++ works.
blood_bank_database.push_back(&d1);
The same function then pushes a pointer to d into this std::vector, and then returns. So, what has been accomplished here? This is what was accomplished here, the end result: the vector gets filled up with pointers to destroyed objects, and all subsequent use of those pointers becomes undefined behavior.
The general name for this kind of a problem is called "pointless use of pointers". This is because nothing of value gets accomplished by using pointers, when none are needed. blood_bank_database can simply be a
vector<donate> blood_bank_database;
and the rest of the code adjusted accordingly. The end result will be much simpler, and less error-prone.

How do I read incrementally to the next line everytime a function is called?C++

for my csc 102 assignment, I need to create a class to hold a student's grades and name. Then output that information to a text file. The grades and name are both read from an input file. I got it to succesfully run one instance of student. However, I do not know how to make the next student object read from the next line.
the input file is in this format:
Jonathan Blythe 87 76 79 88
Jessica Blake 87 79 58 86
Jonathan Lee 88 86 69 100
Joseph Blake 78 89 50 69
My first Student object Student a; reads the correct line. However, when I call the function again for another Student object Student b;, it still reads the first line, and overwrites the output file. I thought if I didn't close the file until the end of main that it may read correctly. I will show the class header file, and the implementation file for Student below.
#include "Student.h"
Student::Student() {
cout << "Default Constructor" << endl;
}
void Student::getscores() {
ifstream infile;
infile.open("input.txt");
infile >> firstName >> lastName;
for (int i = 0; i <= 3; i++) {
infile >> scores[i];
}
infile.close();
}
void Student::getaverage() {
average = 0;
for (int i = 0; i < 4; i++) {
average = average + scores[i];
}
average = average / 4;
}
void Student::print()const {
ofstream outfile;
outfile.open("output.txt");
outfile << firstName << " " << lastName << endl;
cout << firstName << " " << lastName << endl;
for (int i = 0; i <= 3; i++) {
cout << scores[i] << " ";
outfile << scores[i] << " ";
}
cout << endl;
outfile << endl;
cout << "Average Score: " << average << endl;
outfile << "Average Score" << average << endl;
cout << "Letter Grade: " << grade << endl;
outfile << "Letter Grade: " << grade << endl;
//outfile.close();
}
void Student::getletter() {
if (average >= 90)
grade = 'A';
else if (average >= 80 && average < 90)
grade = 'B';
else if (average >= 70 && average < 80)
grade = 'C';
else if (average >= 60 && average < 70)
grade = 'D';
else if (average < 60)
grade = 'F';
}
Student::~Student() {
}
and
#pragma once
#include<iostream>
#include<string>
#include <fstream>
using namespace std;
class Student
{
string lastName;
string firstName;
int scores[4] = { 0,0,0,0 };
int average = 0;
char grade = 'n';
public:
Student();
Student(string, string, int, int, int, int, char);
~Student();
void getscores();
void getaverage();
void getletter();
void print()const;
};
How do I read incrementally to the next line everytime a function is called?
One option is to pass the input stream as an argument to the function.
You should read the input.txt line by line, for each line you need to parse to get the firstName, lastName, scores then use them to create a new object of Student class (you need some changes of Student class to create object from name, set scores, etc.)
I suggest the code skeleton is something like below:
char line[128] = {0,};
ifstream infile;
infile.open("input.txt");
if (!infile.is_open()) {
return;
}
while (infile.getline(line, sizeof(line) - 1)) { // read content of next line then store into line variable
// parse content of line to get firstName, lastName, scores
...
// create new object of Student class from firstName, lastName, scores you got
...
// clear content in line
memset(line, '\0', sizeof(line));
}

Calling for function, only returning 0

Alrighty, the goal of what I am trying to do right now is call the function getSingleStudentInfo, which contains the student's number, last name, and age. In the end this program is designed to do two things, the first being the single student info, the second, printing out an array of 20 students. Disregard the second part, as I have not really gotten into that part yet, so ignore anything involving vectors.
The problem that I am having is that in main the first thing that the program will do is ask you to press 1 for the single info or 2 for the full 20 peoples info. The program compiles fine, but what happens is, no matter what number you enter, the program will say "process returned 0 (0x0)" and be done, I'm having a hard time figuring out why it is doing that instead of printing out the single students info, being "student's ID number is 400" "student's last name is: Simmons" "student's age is: 20"
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct Student {
int studentNumber = 400;
string lastName = "Simmons";
int age = 20;
};
Student s;
int selection;
vector<int> studentNumber (20);
vector<string> lastName;
vector<int> age (20);
void getSingleStudentInfo (int studentNumber, string lastName, int age) {
cout << "Student's ID number is: ";
cout << s.studentNumber << endl;
cout << "Student's last name is: ";
cout << s.lastName << endl;
cout << "Student's age is: ";
cout << s.age << endl;
return;
};
int main()
{
cout << "Press '1' to see a single student data entry" << endl;
cout << "Press '2' to see all 20 student records" << endl;
cin >> selection;
if (selection == 1) {
getSingleStudentInfo;
};
/*for (vector<int>::size_type i = 0; i <= 20; i++)
{
cout << "Student's ID number is: " << 400 + i << endl;
}
return 0;*/
}
You need to call the function, e.g.
if (selection == 1)
{
getSingleStudentInfo(7, "Johnson", 20);
}
However, it seems like by the implementation, this should be a method off of the student itself
struct Student {
int studentNumber = 400;
string lastName = "Simmons";
int age = 20;
void getSingleStudentInfo() const;
};
Then you'd call it off a Student instance
Student s{400, "Simmons", 20};
s.getSingleStudentInfo();
Then if you had a vector of Student you could do
std::vector<Student> students; // assume this has been populated
std::for_each(begin(students),
end(students),
[](const Student& s){s.getSingleStudentInfo();});
To print in columns, you could change your function to something like
void Student::getSingleStudentInfo()
{
cout << s.studentNumber << '\t'
<< s.lastName << '\t'
<< s.age << endl;
};

Initilisation of variable in constructor not working but instead giving me a random number

As you probably gathered from the title I'm having an error initialising the variable 'passNum' in the constructor of my file 'booking.h'
The file contains the booking class for a flight reservation program and I'd like to initialise passNum to 0 because initially there are no passengers on the flight. However I keep getting the message "flight is full" which was in place for the user to see whether there was any space left on the flight or not. SO, to see the error I added a cout in order to see what number was actually stored in passNum. The output was '28080747' however the number changes every time I compile and run.
Booking file...
//Booking class - Scotia Airlines
//Zac Mazs
//This class will reserve a seat for passenger
#include <iostream>
#include <string>
#include "flight.h"
using namespace std;
class Booking{
public:
// default constructor
Booking()
{
int passNum = 0; // initialise passenger number to 0
totalSeats = 24; // total seats on plane
fName = "empty";
sName = "empty";
busName = "empty";
}
// accessor methods
void setPassNum(int p){passNum = p;}
string getFname(){return fName;}
string getSname(){return sName;}
string getBusName(){return busName;}
void addBooking()
{
if (passNum >= totalSeats) // if the number of passengers exceeds 24 then display flight-full message
{
cout << passNum;
cout <<"Flight is full";
}
else
{
cout << "\tBooking Menu \n\n";
cout << "Please select ticket type: \n";
cout << "1- Business \n";
cout << "2- Western Isles \n";
cout << "3- Ordinary \n";
cin >> livesAt;
// This will be used to calc total cost for each passenger dependant on ticket type
if(livesAt == 1)
{
discount = 0.75;
cout << "Please enter your business name\n";
cin >> busName;
}
else if (livesAt == 2)
{
discount = 0.90;
}
else if(livesAt == 3)
{
discount = 1.0;
}
else
{
cout << "Error, please choose 1,2 or 3";
}
// Calculation - Standard ticket price is 60 Beans
tickPrice = 60.0;
tCost = (tickPrice * discount);
bool booked = false;
for(int ROW = 0; ROW < 4 && !booked; ROW++)
{
for(int COL = 0; COL < 6 && !booked; COL++)
{
if(f.isAvailable(ROW,COL) == true)
{
cout << "Please enter your first name \n";
cin >> fName;
cout << "Please enter your second name \n";
cin >> sName;
//create new string fullName from fName and sName
fullName == fName + " " + sName;
f.setName(ROW,COL, fullName);
f.setAvailable(ROW,COL,0);
f.seatArray[ROW][COL].available++;
booked = true;
// increment pass num/decrement totalSeats
totalSeats--;
passNum++;
// Message on screen for customer displaying cost of flight
cout << "*******************************\n";
cout << "\tBooking for "; cout << fName + " " + sName; cout << " confirmed.\n";
cout << "\tTotal cost = " << tCost << " GBP.\n";
}//end of if
}//end of for2
}//end of for1
}//end else
}// End of addBooking function
private:
//Declare all variables
string fName, sName, busName, fullName;
int livesAt, totalSeats;
int passNum;
float discount, tickPrice, tCost;
Flight f;
Seat s;
Passenger p;
};// End of addBooking class
Any thoughts? I really appreciate the help!
Thanks in advance.
In the constructor, passNum is declared locally (it hides the private class-level definition).
Change to:
Booking()
{
/*int*/ passNum = 0; //initialise passenger number to 0
totalSeats = 24; // total seats on plane
fName = "empty";
sName = "empty";
busName = "empty";
}
The problem is the int in
int passNum = 0; // initialise passenger number to 0
You are not assigning to the member variable, you are creating a new local variable with the same name.
To fix, remove the int.

Functions and structures in C++

/*I got stumped within my code. I think classes will be simpler than structures, but the chapter within my book makes me do structures. : / I am currently getting an error message that my function was not matched up for an overloaded function. The book does talk about them, but the examples of overloading functions in the book aren't helping me out. Also the book wants me to enter account numbers and fill in the objects and when they are asked for an account number they should have the opportunity to "QUIT" entering numbers and proceed onto the next part of the program; that whole way of thinking has my brain a bit fried and I was hoping I could get some help. I apologize if the formatting of my code is messy, I tried to reformat it within here so it would all go into the code brackets.
The Error happens at line... 161 at the displayAccounts function. Parameters were different within the top and bottom of the two functions I changed it and it works. I am going to go over different parts and if its correct post the correct code.*/
I figured out exactly the question that I need. I need the "QUIT" loop to be allowed to be followed up within the account numbers. This would allow the user to enter in a 0 at any time when asked to enter an account number and this was what was confusing me the most.
#include <iostream>
#include <iomanip>
using namespace std;
struct BankAccount
{
void enterAccountsData(BankAccount *accounts);
void computeInterest(BankAccount *accounts);
void displayAccounts(BankAccount *accounts, const int QUIT);
int accountNum; // holds the account number.
double accountBal; // holds the account balance.
double annualInterest; // holds the interest rate.
int term; // holds the term for the accounts.
};
int main()
{
const int MAX_ACCOUNTS = 100; // The maximum number of bank accounts.
const int QUIT = 0; // sentinal value.
int input;
int num = 0;
BankAccount data[MAX_ACCOUNTS];
BankAccount display;
cout << "Enter " << QUIT << " to stop, otherwise enter 1 and procreed.";
cin >> input;
while(true)
{
if(input != QUIT)
{
data[MAX_ACCOUNTS].enterAccountsData(data);
data[MAX_ACCOUNTS].computeInterest(data);
}
else
{
break;
}
}
display.displayAccounts(data, QUIT);
//system("pause");
return 0;
}
void BankAccount::enterAccountsData(BankAccount *accounts)
{
cout << setprecision(2) << fixed;
const int NUM_OF_ACCOUNTS = 100; // the number of bank accounts. (change the number for more bank accounts)
int found;
int quit = 0;
/* First for loop which asks and holds the account information
entered in by the user. */
for(int num = 0; num < NUM_OF_ACCOUNTS; num++)
{
do
{
found = 0;
cout << "Enter in account # " << (num + 1) << endl;
cin >> accounts[num].accountNum; // holds the value of the account number
// Checks if the account number is valid.
while(accounts[num].accountNum < 999 || accounts[num].accountNum > 10000)
{
cout << "Account number must be four didgets:" << endl;
cin >> accounts[num].accountNum;
}
// Checks if the account numbers are the same.
for(int check = 0; check < num; check++)
{
while(accounts[num].accountNum == accounts[check].accountNum)
{
cout << endl << "Account Numbers cannot be the same, enter in a new account number." << endl;
found = 1;
break;
}
}
} while(found); // end of do while.
// Holds the values for the account balances.
cout << "Enter the accounts balance." << endl;
cin >> accounts[num].accountBal;
// Makes sure that the account balance is not negative.
while(accounts[num].accountBal < 0)
{
cout << "Account cannot have a negitive balance." << endl;
cin >> accounts[num].accountBal;
}
// Holds the interest rate.
cout << endl << "Enter the interest rate for account # " << (num + 1) << endl;
cin >> accounts[num].annualInterest;
// Makes sure the interest rate is valid
while(accounts[num].annualInterest > 0 && accounts[num].annualInterest > 0.15)
{
cout << endl << "Annual interest must be from 0 to 0.15." << endl;
cin >> accounts[num].annualInterest;
}
// Makes sure the interest rate is not negetive
while(accounts[num].annualInterest < 0)
{
cout << endl << "Interest rate cannot be negetive" << endl;
cin >> accounts[num].annualInterest;
}
// Holds the value for the length of the interest.
cout << endl << "How many years will this interest rate be held for? " << endl;
cin >> accounts[num].term;
//Checks for valid length of time for the term held
while(accounts[num].term < 0 || accounts[num].term > 11)
{
cout << "The Term must be greater than 1 and should not exceed 10" << endl;
cin >> accounts[num].term;
}
}
cout << "If you wish to stop enter 0 otherwise type 1 to proceed" << endl;
cin >> quit;
if(quit = 0)
{
return;
}
}
void BankAccount :: computeInterest(BankAccount *accounts)
{
const int NUM_OF_ACCOUNTS = 100; // the number of bank accounts.
const int MONTHS_IN_YEAR = 12;
double total = 0;
double average = 0;
for(int num = 0; num < NUM_OF_ACCOUNTS; num++)
{
/*Goes through the term year and calculates the total
of each account balance. Then calculates the average. */
for(int year = 0; year < accounts[num].term; year++)
{
for(int month = 0; month < MONTHS_IN_YEAR; month++)
{
accounts[num].accountBal = (accounts[num].accountBal * accounts[num].annualInterest) + accounts[num].accountBal;
}
int month = 1;
cout << endl << "Total amount for account # " << (num + 1) << " is: " << accounts[num].accountBal << endl ;
total += accounts[num].accountBal;
cout << endl << "The total amount of all accounts is: " << total << endl;
}
}
average = total / NUM_OF_ACCOUNTS;
cout << "Average of all the bank accounts is: " << average << endl;
}
void BankAccount :: displayAccounts(BankAccount *accounts)
{
int input = 0;
int found;
const int MAX_ACCOUNTS = 100;
int quit = 0;
cout << endl << "Which account do you want to access?" << endl <<
"To stop or look at none of the account numbers type: " << quit << endl;
cin >> input;
for(int num = 0; num < MAX_ACCOUNTS; num++)
{
while(num < MAX_ACCOUNTS && input != accounts[num].accountNum)
{
num++;
}
if(input == accounts[num].accountNum) // This if sees if an account matches what the user entered.
{
cout << "Account: " << accounts[num].accountNum << endl << "Balance is: " <<
accounts[num].accountBal << endl << "Interest rate is: " << accounts[num].annualInterest;
cout << endl << "Enter another account number or type 0 to quit." << endl;
found = 1;
cout << endl;
cin >> input;
}
if(found == 0)
{
cout << "Sorry that account doesn't exist. Enter another account number." << endl;
cin >> input;
}
}
}
In C++, classes and structs are exactly the same constructs. They are, in fact, one thing — a User-Defined Type.
There is a different that is invoked depending on whether you used the keyword struct or class to define your UDT, and that is that class-key defaults to private member access and private inheritance, whereas struct-key defaults to both being public.
Other than this syntax difference, you can use either without worrying about one being "simpler" than the other.
Anyway, your compiler error (please provide it next time) is probably due to a declaration/definition mismatch.
Your declaration:
void displayAccounts(BankAccount *accounts, const int QUIT);
Start of your definition:
void BankAccount :: displayAccounts(BankAccount *accounts) {
The start of the definition should be
void BankAccount::displayAccounts(BankAccount* accounts, const int QUIT) {
to match. I've also fixed your spacing to be nicer. :)
void displayAccounts(BankAccount *accounts, const int QUIT);
... looks different between declaration and definition. Second parameter is missing in the definition.
Not sure what your question is, but classes and structs in C++ are equivalent except that fields are public by default in structs, but private by default in classes.
In the struct’s displayAccounts() member declaration you have:
void displayAccounts(BankAccount *accounts, const int QUIT);
and when defining the method later:
void BankAccount :: displayAccounts(BankAccount *accounts)
You have just missed
const int QUIT
parameter for the member function definition.