I have written a simple program that displays total jars of salsa sold, as well as the least and greatest types of salsa sold. The program works fine unless I intentionally use bad user input such as letters and negative numbers. The call to function inputValidation seems to work until I am finished inputting all the jars sold for each salsa type. Then it displays most of the results and crashes.
// this program allows a business to keep track of sales for five different types of salsa
#include <iostream>
#include <string>
#include <climits>
using namespace std;
// function prototype
int inputValidation(int);
int main()
{
const int SIZE = 5;
string names[SIZE] = { "Mild", "Medium", "Sweet", "Hot", "Zesty" };
int jars[SIZE];
int totalSold = 0;
// get the number of jars sold for each salsa
int tempJars;
for (int i = 0; i < SIZE; i++)
{
cout << "Enter the number of " << names[i] << " salsa jars sold this past month.\n";
cin >> tempJars;
// call to input validation function
jars[i] = inputValidation(tempJars);
totalSold += jars[i];
}
// determine the lowest and highest salsa type sold
int lowest = jars[0],
highest = jars[0],
leastType,
greatestType;
for (int i = 0; i < SIZE; i++)
{
if (jars[i] < lowest)
{
lowest = jars[i];
leastType = i;
}
if (jars[i] > highest)
{
highest = jars[i];
greatestType = i;
}
}
// display results
for (int i = 0; i < SIZE; i++)
{
cout << "You sold " << jars[i] << " jars of " << names[i] << " salsa.\n";
}
cout << "You sold a total of " << totalSold << " jars of salsa.\n"
<< names[leastType] << " salsa sold the least amount of jars, which was " << lowest << " jars sold.\n"
<< names[greatestType] << " salsa sold the most amount of jars, which was " << highest << " jars sold.\n";
}
/*
definition of function inputValidation
inputValidation accepts an int value as its argument. It determines that the value is a number that is
greater than 0. If it is not, then the user is prompted to input an acceptable value. the value is
returned and stored in the corresponding element of the jars array.
*/
int inputValidation(int jars)
{
do
{
while (cin.fail())
{
cin.clear(); // clear the error flags
cin.ignore(INT_MAX, '\n'); // return cin to usable state
cout << "You may only enter non negative numbers. Please try again.\n";
cin >> jars;
}
if (jars < 0)
{
cout << "You may only enter non negative numbers. Please try again.\n";
cin >> jars;
}
} while (jars < 0);
return jars;
}
If jars[0] happens to be the smallest of the five, then leastType is never initialized and contains random garbage. Then an attempt to access names[leastType] exhibits undefined behavior.
Similarly, if jars[0] is the greatest, then greatestType is never initialized.
Related
Hi there apologise if my question is poorly worded, I'm struggling to find a solution to my problem.
The purpose of my program is to allow the user to enter predefined bar codes that associate with items and a price. The user enters as many barcodes as they want, and when they're done they can exit the loop by pressing "F" and then total price for all the items is displayed.
This is my code so far, I'm very new to programming..
#include <iostream>
#include <iomanip>
using namespace std;
int index_of(int arr[], int item, int n) {
int i = 0;
while (i < n) {
if(arr[i] == item) {
return i;
}
i++;
}
return -1;
}
const int SIZE = 10;
int main()
{
string item [SIZE] = {"Milk", "Bread", "Chocolate", "Towel", "Toothpaste", "Soap", "Pen", "Biscuits", "Lamp", "Battery"};
int barcode [SIZE] = {120001, 120002, 120003, 120004, 120005, 120006, 120007, 120008, 120009, 120010};
float price [SIZE] = {10.50, 5.50, 8.00, 12.10, 6.75, 5.20, 2.00, 4.45, 20.50, 10.00};
cout << "*************************************************************" << endl;
cout << "WELCOME TO THE CHECKOUT SYSTEM" << endl;
cout << "Please scan a barcode or manually enter the barcode ID number" << endl;
cout << "*************************************************************\n" << endl;
int newBarcode;
while (true){
cout << "Please enter a barcode (Type 'F' to finish): ", cin >> newBarcode;
int index = index_of(barcode, newBarcode, (sizeof(barcode) / sizeof(barcode)[0]));
cout << "\n>> Name of item: " << item[index] << endl;
cout << ">> Price of item: \x9C" << setprecision (4)<< price[index] << endl;
cout << ">> " <<item[index] << " has been added to your basket. \n" << endl;
float total = 0 + price[index];
cout << ">> Your current basket total is: \x9C" << setprecision(4) << total << endl;
/*float total = 0;
float newtotal = 0;
price[index] = total;
total = newtotal;
cout << ">> " << "Basket total: " << newtotal << endl; */
}
return 0;
}
You will need to iterate over all items and add their value to a variable. You can do it the old way:
float sum = 0;
for(int i = 0; i < SIZE; i++) {
sum += price [i];
}
Or the C++11 way:
float sum = 0;
for(float p : price) {
sum += p;
}
However I must point out a few important issues with your code:
Your array has a fixed size but user can enter as many entries as he wants. To avoid this issue, use vector. It behaves like array but has dynamic size. Simply use push_back() to add a new element.
Don't use separate containers (arrays) for the same group of objects. It's a bad coding practice. You can define a structure for product which will contain name, barcode and price, then make one container for all of the products.
Edit
I'm sorry, I misunderstood your problem. There are many ways to solve this, the most elegant way is to create a map where key is the bar code and value is your product object or just a price.
map<int, float> priceMap;
priceMap.insert(pair<int, float>([your bar code here], [your price here]))
Afterwards just create a vector of bar codes, fill it with user data and iterate over it sum all prices:
float sum = 0;
for(int b : userBarcodes) {
sum += priceMap.at(b);
}
You are trying to read from cin into an int. As you decide to put a stopping condition on 'F' input you must read into a string. Then decide what to do with the value. You will need to check if the input is an int or not. You can do it as given here or here.
Or you may change the stopping condition to a less likely integer like -1. And make sure you always read an int into newBarcode.
There are various small errors which are hard to list out. I have changed them in the code below which is implementing point 2 (You have to add the stopping condition).
One of the error or wrong practice is to declare new variables inside a loop. In most cases you can declare the variables outside and change there values in the loop.
I replaced (sizeof(barcode) / sizeof(barcode)[0] with SIZE as the lists are predefined and unchanging. Anyways you should use (sizeof(barcode) / sizeof(barcode[0]) for length calculation.
#include <iostream>
#include <iomanip>
using namespace std;
int index_of(int arr[], int item, int n) {
int i = 0;
while (i < n) {
if(arr[i] == item) {
return i;
}
i++;
}
return -1;
}
const int SIZE = 10;
int main()
{
string item [SIZE] = {"Milk", "Bread", "Chocolate", "Towel", "Toothpaste", "Soap", "Pen", "Biscuits", "Lamp", "Battery"};
int barcode [SIZE] = {120001, 120002, 120003, 120004, 120005, 120006, 120007, 120008, 120009, 120010};
float price [SIZE] = {10.50, 5.50, 8.00, 12.10, 6.75, 5.20, 2.00, 4.45, 20.50, 10.00};
cout << "*************************************************************" << endl;
cout << "WELCOME TO THE CHECKOUT SYSTEM" << endl;
cout << "Please scan a barcode or manually enter the barcode ID number" << endl;
cout << "*************************************************************\n" << endl;
int newBarcode;
float total = 0;
int index;
while (true){
cout << "Please enter a barcode (Type -1 to finish): \n";
cin >> newBarcode;
while(cin.fail()) {
cout << "Not an integer" << endl;
cin.clear();
cin.ignore(100,'\n');
cin >> newBarcode;
}
index = index_of(barcode, newBarcode, SIZE);
cout << index;
if (index == -1) {
cout << "Apologies here for unsupported barcode\n";
continue;
} else {
cout << ">> Name of item: " << item[index] << endl;
cout << ">> Price of item: " << price[index] << "\n";
cout << ">> " <<item[index] << " has been added to your basket. \n";
total = total + price[index];
cout << ">> Your current basket total is: " << total << "\n";
}
}
return 0;
}
Your question could be more helpful to others if you find out what is wrong with your implementation and ask implementation specific questions which will probably be already answered. Asking what is wrong with my code is not quite specific.
I am coming to a problem where when negative numbers are entered that it shows an error message. libc++abi.dylib: terminating with uncaught exception of type std::bad_alloc: std::bad_alloc. is there a way to detect that error when negative numbers and entered with a message: Enter 0 or greater. So, can anyone help me solve this. Thanks for the help.
I tried by doing this:
int students = 0;
while (students <= 0) {
cout << "How many students? ";
cin >> students;
if (students <= 0) {
cout << "Enter 0 or greater";
}
}
int testsScore = 0;
while (testsScore <= 0) {
cout << "How many tests per student? ";
cin >> testsScore;
if (testsScore <= 0) {
cout << "Enter 0 or greater";
}
}
Main Code:
#include <iostream> // input out stream library.
#include <iomanip> // parametic manipulators library for our table.
using namespace std;
//MARK: Structure to use the following data given in the instructions.
struct student_information {
//MARK: Student name.
string studentName;
//MARK: Student ID number.
int id;
//MARK: Pointer to an array of test scores.
int *tests;
//MARK:Average test score.
double average;
//MARK: Course grade.
char grade;
};
//MARK: The main() method should keep a list of test scores for group of students.
int main() {
// MARK: Declare variables.
int numberOfStudents;
int testScores;
//MARK: So, in our logic it should ask the user how many test scores there are to be,
// and how many students there are.
// It should then dynamically allocate an array of structures. However,
// each structure tests member should point to a dynamically allocated array
// that will hold the test scores according to our instructions.
cout << "How many students?";
cin >> numberOfStudents;
cout << endl;
cout << "How many tests per student? ";
cin >> testScores;
cout << endl;
student_information *pointerToArray = new student_information[numberOfStudents];
for (int i = 0; i < numberOfStudents; i++) {
pointerToArray[i].tests = new int[testScores];
}
//MARK: So, this is when the array has been allocated,
//the program should ask for the student ID number and all the scores for each
// every student.
for (int i = 0; i < numberOfStudents; i++) {
cout << "Student Name: ";
cin >> pointerToArray[i].studentName;
cout << endl;
cout << "ID Number: ";
cin >> pointerToArray[i].id;
cout << endl;
for (int v = 0; v < testScores; v++) {
cout << " Test # " << (v + 1) << " : ";
//MARK: Checking to see all the data is entered for each student / member.
cin >> pointerToArray[i].tests[v];
cout << endl;
// MARK: Checking if negative numbers are entered for any test scores.
while(pointerToArray[i].tests[v] < 0 || pointerToArray[i].tests[v] > 100) {
cout << "Enter 0 or greater";
cin >> pointerToArray[i].tests[v];
cout << endl;
}
}
}
//MARK: The average test score should be calculated and stored in the average member of each structure.
//The course grade should be computed on the basis of the following grading scale:
// Average Test Grade Course Grade
// 91-100 A
// 81-90 B
// 71-80 C
// 61-70 D
// 60 or below F
for (int i = 0; i < numberOfStudents; i++) {
double add = 0;
for(int x=0; x < testScores; x++)
add = add + pointerToArray[i].tests[x];
pointerToArray[i].average = add / testScores;
//MARK: The course grade will be stored in the grade member structure.
//After the data entry has been calculated.
if(pointerToArray[i].average >= 91 && pointerToArray[i].average <= 100)
pointerToArray[i].grade = 'A';
else if(pointerToArray[i].average >= 81 && pointerToArray[i].average <= 90)
pointerToArray[i].grade = 'B';
else if(pointerToArray[i].average >= 71 && pointerToArray[i].average <= 80)
pointerToArray[i].grade = 'C';
else if(pointerToArray[i].average >= 61 && pointerToArray[i].average <= 70)
pointerToArray[i].grade = 'D';
else if(pointerToArray[i].average < 60)
pointerToArray[i].grade = 'F';
//MARK: Displaying the table to list each students name, ID number,
//average test score and the course grade.
for(int i=0; i < numberOfStudents; i++)
{
cout << "Student Name: " << setw(19) << left << pointerToArray[i].studentName <<
" ID Number: " << setw(19) << pointerToArray[i].id <<
" Average test score: " << setw(15) << pointerToArray[i].average <<
" Grade: " << setw(15) << pointerToArray[i].grade << endl;
}
return 0;
}
}
If negative numbers are entered for numberOfStudents or testsScore, then
student_information *pointerToArray = new student_information[numberOfStudents];
or
pointerToArray[i].tests = new int[testScores];
try to allocate memory with huge amount. When this fails std::bad_alloc is thrown and OP doesn't catch it. Hence, it is catched outside OPs main().
The array size in new[] expects a size_t → an unsigned value and silently converts the provided signed. E.g. -1 becomes 0xffffffff (32 bit) or even bigger.
#include <iostream>
#include <iomanip>
int main(int argc, char* argv[])
{
int value = -1;
size_t size = value;
std::cout << "size: " << size << " = 0x" << std::hex << size << '\n';
try {
int *mem = new int[size];
} catch (const std::exception &error) {
std::cerr << error.what() << '\n';
}
return 0;
}
Output:
size: 18446744073709551615 = 0xffffffffffffffff
std::bad_array_new_length
Live Demo on coliru
OP should add a check that input numbers are > 0.
It puzzled me a bit that my sample throws std::bad_array_new_length (instead of the std::bad_alloc as reported by OP). Investigating a bit into this I found
it's precisely documented this way (e.g. in cppreference.com)
Otherwise, the new-expression does not call the allocation function, and instead throws an exception of type std::bad_array_new_length or derived from it
std::bad_array_new_length is derived from std::bad_alloc.
Assuming you're trying to input negative numbers to the students and test scores, you just need to add a similar while loop to test them as you do bellow for the grades...
cout << "How many students?";
cin >> numberOfStudents;
while (numberOfStudents <= 0) {
cout << "Number of students should be greater than 0";
cin >> numberOfStudents;
cout << endl;
}
cout << endl;
As noted in the previous comments, new[] expects size_t, meaning an unsigned number https://en.cppreference.com/w/cpp/types/size_t
#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
int numofEmployees();
int daysMissed(int);
int AverageMissed(int, int);
int main()
{
cout << "Welcome to employee absentee calculator!" << endl;
int numEmployees = numofEmployees();
int Missed = daysMissed(numEmployees);
double misAverage = AverageMissed(numEmployees, Missed);
cout << "There are " << numEmployees << " in the company. They have missed " << Missed << " days total. On average, they have missed " << misAverage << " days." << endl;
return 0;
}
int numofEmployees() {
cout << "How many employees are in your company? ";
int employees;
cin >> employees;
while (employees < 1) {
cout << "Employee count must 1 or greater!" << endl;
}
return employees;
}
int daysMissed(int numEmployees) {
int Absence, totAbsence = 0;
for (int i = numEmployees; i < numEmployees; i++) {
cout << "How many days has each employee missed this passed year? ";
cin >> Absence;
totAbsence += Absence;
}
while (Absence < 0) {
cout << "Values entered must be positive numbers!" << endl;
cin >> Absence;
}
return totAbsence;
}
int AverageMissed(int numEmployees, int Missed){
double Average;
Average = double(numEmployees) / double(Missed);
return Average;
}
This code is being used to calculate the average number of employee absences by way of using three functions. The second function is not working correctly as it is not being called properly by the main. This is for a school assignment.
The problem is daysMissed - if numEmployees is <= 0, then Absense will be uninitialized. But, you say, "I check that in numofEmployees" - the problem is that the compiler doesn't do that sort of whole-program analysis before issuing these warnings.
There is another problem: daysMissed is wrong (twice). If there are two employees, and I enter -2 and 1, there will be no error for the negative number. If on the other hand, if I enter 1 and -2, you never correct totAbsence. You would be much better off writing a little function which reads a number >= some limit in a loop, and keeps prompting until given the correct value. Something like:
int read(const char* prompt, const char* err_prompt, int limit) {
cout << prompt << endl;
for(;;) {
int result;
cin >> result;
if (result >= limit) {
return result;
}
cout << err_prompt << endl;
}
}
Then daysMissed becomes much pleasanter to write - and you can use the same function to read the number of employees (which will go into an infinite loop at the moment)
You should also validate a division by zero plus change the return type.
double AverageMissed(int numEmployees, int Missed){
if (Missed > 0) return double(numEmployees) / Missed;
return 0;
}
by the way, there is no need to cast both operands in the division (/). Casting one of them will be enough to return a double type.
I do not get arrays, Im sure there are easier ways to make this program but I must do it the teacher's way and I am lost.
This is the assigment:
I do not get how I should go about these arrays. most confusing thing I seen by far.
What I would like is a guide or help on how i should program these arrays or how I should program arrays period. Not asking to do the rest for me, I already know how to do most of this, its just the arrays I like to know how to do.
This is my current program:
#include<iostream>
using namespace std;
void getPoints(int pPossible[], double pEarned[], int numItems, int limit);
int sumArray(double
void getpoints(int pPossible[], double pEarned[], int numItems, int limit)
{
int count;
while (limit == limit)
{
cout << "Input grade points for a category in the gradebook: " << endl
<< "How many items available in the category?: ";
cin >> numItems;
cout << endl;
if(numbItems > limit)
{
cout << "The Value exceeds the maximum number of items." << endl;
continue;
}
break;
}
count=1;
for(count=1; count<numItems; count++)
cout << "Enter points then points possible for Item " << count << ": ";
cin << pEarned[count] << pPossible[count];
return 0;
}
C++ array indexes are zero-based, so you should use zero for the initial value in the for loop. Also, you're missing the braces for the for loop body; as it is, it will run the cout line numItem-1 times and the cin line just once.
Another thing: the operators in the for's cin line should be >>, not <<. You want input here, not output.
Finally, like #ebyrob said, make numItems a reference parameter (it would be clearer for the caller to use a pointer instead, but the assignment asked for a reference parameter).
void getpoints(int pPossible[], double pEarned[], int& numItems, int limit)
{
//Read number of items
while (true)
{
cout << "Input grade points for a category in the gradebook: " << endl
<< "How many items available in the category?: ";
cin >> numItems;
cout << endl;
if(numItems >= limit)
{
cout << "The Value exceeds the maximum number of items." << endl;
continue;
}
break;
}
//Read earned and possible for each item
for(int count=0; count<numItems; count++)
{
cout << "Enter points then points possible for Item " << count << ": ";
cin >> pEarned[count] >> pPossible[count];
}
return 0;
}
/*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.