Overloading operators..getting a logical error - c++

I am having some trouble When I run my current program. I can add any number of transactions within this account balance, but when I go past the first array value and enter information, it displays a memory location.. Whats my problem in my code then here.
for(int i = 0; i < ACCTS; ++i)
{
do
{
debitCredit = accounts[x].operator+=(accounts[x]);
cout << "Account Balance is:$" << debitCredit << endl;
cout << "Enter " << QUIT << " to stop transactions." << endl;
cin >> selection;
}while(selection != QUIT);
++x;
}
The source code for this is here:
//Alex Weir
// Case 2 Chapter 9
#include <iostream>
#include <iomanip>
using namespace std;
class BankAccount
{
friend ostream& operator<<(ostream&, const BankAccount&);
friend istream& operator>>(istream&, BankAccount&);
private:
int accountNum;
int increaseAccountNum;
double accountBal;
double annualIntRate;
double debitCredit;
public:
BankAccount();
BankAccount(int,int,double,double,double);
int operator==(const BankAccount&);
void operator<(const BankAccount&);
void operator>(const BankAccount&);
double operator+=(BankAccount);
int operator+(BankAccount);
void displayAccounts();
};
double BankAccount::operator+=(BankAccount account)
{
cout << "How much money would you like to deposit or withdraw?" << endl <<
" Enter a negative amount to withdraw." << endl;
cin >> debitCredit;
debitCredit = debitCredit + account.accountBal;
return debitCredit;
}
int BankAccount::operator+(BankAccount account)
{
int increment;
int accountNum = increment + account.accountNum;
return accountNum;
}
void BankAccount::operator>(const BankAccount& accounts)
{
if(accountBal > accounts.accountBal)
{
cout << "Account Balance is greater than another account." << endl;
}
else
{
cout << "Account Balance is less than another account." << endl;
}
}
void BankAccount::operator<(const BankAccount& accounts)
{
if(accountBal < accounts.accountBal)
{
cout << "Account Balance is less than another account." << endl;
}
else
{
cout << "Account Balance is greater than another account." << endl;
}
}
BankAccount::operator==(const BankAccount& acctNumb)
{
int isTrue = 0;
if(accountNum == acctNumb.accountNum)
isTrue = 1;
return isTrue;
}
ostream& operator << (ostream& out, const BankAccount& Accounts)
{
cout << endl;
out << "Account #" << Accounts.accountNum << endl;
out << "Account Balance:$" << Accounts.accountBal << endl;
out << "Account interest rate: " << Accounts.annualIntRate << endl;
cout << endl;
return out;
}
istream& operator >> (istream& in, BankAccount& Accounts)
{
cout << "Enter Account # " << endl;
in >> Accounts.accountNum;
cout << "Enter Account Balance: $";
in >> Accounts.accountBal;
cout << endl << "Enter Account Interest Rate: " << endl;
in >> Accounts.annualIntRate;
cout << endl;
return in;
}
BankAccount::BankAccount()
{
accountNum = 0;
accountBal = 0;
annualIntRate = 0;
increaseAccountNum = 0;
debitCredit = 0;
}
BankAccount::BankAccount(int acctNum, int increment, double acctBal, double intRate, double debCred)
{
accountNum = acctNum;
accountBal = acctBal;
annualIntRate = intRate;
increaseAccountNum = increment;
debitCredit = debCred;
}
void BankAccount::displayAccounts()
{
cout << "Account # " << accountNum << endl;
cout << "Account balance:$" << accountBal << endl;
cout << "Account Interest Rate: " << annualIntRate << endl;
cout << endl;
}
int main()
{
const int ACCTS = 5;
const int QUIT = 0;
int x, selection;
double debitCredit = 0.0;
BankAccount accounts[ACCTS];
cout << "Enter Bank account information for: " << ACCTS << " accounts." << endl;
for(x = 0; x < ACCTS; ++x)
{
accounts[x].displayAccounts();
}
for(int i = 0; i < ACCTS; ++i)
{
do
{
debitCredit = accounts[x].operator+=(accounts[x]);
cout << "Account Balance is:$" << debitCredit << endl;
cout << "Enter " << QUIT << " to stop transactions." << endl;
cin >> selection;
}while(selection != QUIT);
++x;
}
for(x = 0; x < ACCTS; ++x)
{
accounts[x].displayAccounts();
}
/*for(x = 0; x < ACCTS; ++x)
{
cout << "Entry #" << (x + 1) << endl;
cin >> accounts[x];
cout << accounts[x];
}
double transactions;
for(x = 0; x < ACCTS; ++x)
{
}*/
Okay now that I have gotten rid of x I continue to have my variable as "i" now, I go through the 5 array elements, but I want to start with array 0 then go through the loop as many times as I want to (still playing with the balance at array element 0) after I hit "stop" or 0 when given the opportunity I want to move onto the 1st array element and go through it, adding and sub tracting for as much as I feel nessacary and repeating this process until I am fine with it. re setting the array's element variable to "i" does not do this and carries over from the last array element used.
system("pause");
return 0;
}

There are several things that might be wrong here:
debitCredit = accounts[x].operator+=(accounts[x]);
Why don't you use i instead of x? Is the value of x even initialized (the code doesn't show)?
Why do you add accounts[x] to itself? In effect you are doubling its value.
Is the accounts array big enough? How is it initialized?
Update
After looking at the extra code you posted: lose the x and use i instead. You are overstepping the bounds of the accounts array.

Related

Output does not include all input for my array

I have this program that is barely started:
#include <iostream>
#include <iomanip>
#include <ctime>
#include <string>
using namespace std;
class Grade
{
public:
string studentID;
int userChoice = 0;
int size = 0;
double* grades = new double[size]{0};
};
void ProgramGreeting(Grade &student);
void ProgramMenu(Grade& student);
string GetID(Grade& student);
int GetChoice(Grade& student);
void GetScores(Grade& student);
int main()
{
Grade student;
ProgramGreeting(student);
ProgramMenu(student);
}
// Specification C1 - Program Greeting function
void ProgramGreeting(Grade &student)
{
cout << "--------------------------------------------" << endl;
cout << "Welcome to the GPA Analyzer! " << endl;
cout << "By: Kate Rainey " << endl;
cout << "Assignment Due Date: September 25th, 2022 " << endl;
cout << "--------------------------------------------" << endl;
GetID(student);
cout << "For Student ID # " << student.studentID << endl;
}
void ProgramMenu(Grade &student)
{
cout << "--------------------------------------------" << endl;
cout << setw(25) << "Main Menu" << endl;
cout << "1. Add Grade " << endl;
cout << "2. Display All Grades " << endl;
cout << "3. Process All Grades " << endl;
cout << "4. Quit Program." << endl;
cout << "--------------------------------------------" << endl;
GetChoice(student);
}
string GetID(Grade &student)
{
cout << "Enter the student's ID: ";
cin >> student.studentID;
if (student.studentID.length() != 8) {
cout << "Student ID's contain 8 characters ";
GetID(student);
}
return student.studentID;
}
int GetChoice(Grade &student)
{
cout << "Enter your selection: ";
cin >> student.userChoice;
if (student.userChoice == 1) {
GetScores(student);
}
else if (student.userChoice == 2)
{
}
else if (student.userChoice == 2)
{
}
else if (student.userChoice == 4)
{
exit(0);
}
else
{
cout << "Please enter 1, 2, 3 or 4" << endl;
GetChoice(student);
}
}
void GetScores(Grade &student)
{
int count = 0;
double score = 0;
cout << "How many test scores would you like to enter for ID# "
<< student.studentID << "? ";
cin >> student.size;
while (count != student.size) {
cout << "Enter a grade: ";
cin >> score;
for (int i = 0; i < student.size; i++) {
student.grades[i] = score;
}
count++;
}
for (int i = 0; i < student.size; i++) {
cout << student.grades[i] << " ";
}
}
I am trying to make sure my array is recording all test scores, but when I output the array in my GetScore function, each element in the array is the same or equal to the last score I entered. For example, if I choose 3 for size and then enter three values of 99.2 86.4 90.1, all three elements will read 90.1.
Why is this happening?
Your Grade class is allocating an array of 0 double elements (which is undefined behavior), and then your GetScores() function does not reallocate that array after asking the user how many scores they will enter, so you are writing the input values to invalid memory (which is also undefined behavior).
Even if you were managing the array's memory correctly (ie, by using std::vector instead of new[]), GetScores() is also running a for loop that writes the user's latest input value into every element of the array, instead of just writing it to the next available element. That is why your final output displays only the last value entered in every element. You need to get rid of that for loop completely.
Try something more like this instead (there are several other problems with your code, but I'll leave those as separate exercises for you to figure out):
class Grade
{
public:
...
int size = 0;
double* grades = nullptr;
};
...
void GetScores(Grade &student)
{
int size = 0;
double score = 0;
cout << "How many test scores would you like to enter for ID# " << student.studentID << "? ";
cin >> size;
if (student.size != size) {
delete[] student.grades;
student.grades = new double[size]{0};
student.size = size;
}
for(int i = 0; i < size; ++i) {
cout << "Enter a grade: ";
cin >> score;
student.grades[i] = score;
}
for (int i = 0; i < size; ++i) {
cout << student.grades[i] << " ";
}
}
Alternatively:
#include <vector>
...
class Grade
{
public:
...
vector<double> grades;
};
...
void GetScores(Grade &student)
{
size_t size = 0;
double score = 0;
cout << "How many test scores would you like to enter for ID# " << student.studentID << "? ";
cin >> size;
student.grades.resize(size);
for (size_t i = 0; i < size; ++i) {
cout << "Enter a grade: ";
cin >> score;
student.grades[i] = score;
}
/* alternatively:
student.grades.clear();
for (size_t i = 0; i < size; ++i) {
cout << "Enter a grade: ";
cin >> score;
student.grades.push_back(score);
}
*/
for (size_t i = 0; i < size; ++i) {
cout << student.grades[i] << " ";
}
}
I removed my for loop from my while loop.
void GetScores(Grade &student)
{
int count = 0;
double score = 0;
cout << "How many test scores would you like to enter for ID# "
<< student.studentID << "? ";
cin >> student.size;
while (count != student.size) {
cout << "Enter a grade: ";
cin >> score;
student.grades[count] = score;
count++;
}
for (int j = 0; j < student.size; j++) {
cout << student.grades[j] << " ";
}
}

Switch statements will not execute

I have an assignment here that I've been working on for the past few hours and have been met with a problem. Whenever I compile and run the program in VS Code it throws me into an infinite loop where the text of the "menu" is printed repeatedly. I imagine this has something to do with the for(;;){ loop at the beginning of the menu.
I've deleted the for(;;){ statement at the beginning of the menu, and the continuous scrolling stopped, but I was unable to input any numbers (cases) and the program, essentially, just printed the menu and that was the end.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
class Student {
string name;
float GPA;
public:
string getName() const
{
return name;
}
float getGPA() const
{
return GPA;
}
void setName(string Name)
{
name = Name;
}
void setGPA(float gpa)
{
GPA = gpa;
}
Student(const string& name, float gpa)
: name(name)
, GPA(gpa)
{
}
Student()
{
}
void printDetails(Student s[], int n)
{
cout << setw(20) << "Name: " << setw(10) << "GPA: " << endl;
cout << "=========================================" << endl;
for (int i = 0; i < n; i++) {
cout << setw(20) << s[i].getName() << setw(10) << s[i].getGPA() << endl;
}
}
float calcAverageGPA(Student s[], int n)
{
float avg = 0;
float sum = 0;
for (int i = 0; i <= n; i++) {
sum += s[i].getGPA();
}
avg = sum / n;
return avg;
}
float getGPAbyName(Student s[], int n, string name)
{
for (int i = 0; i <= n - 1; i++) {
if (s[i].getName() == name)
return s[i].getGPA();
}
return -1;
}
void showListByGPA(Student s[], int n, float gpa)
{
cout << setw(20) << "Name: " << setw(10) << "GPA: " << endl;
cout << "=========================================" << endl;
for (int i = 0; i < n - 1; i++) {
if (s[i].getGPA() > gpa)
;
cout << setw(20) << s[i].getName() << setw(10) << s[i].getGPA() << endl;
}
}
};
int main()
{
int n = 0;
int ch;
Student s[50];
string name;
float GPA;
float avg = 0;
cout << "======================" << endl;
cout << "(1): Add a student" << endl;
cout << "(2): Print the details of a student" << endl;
cout << "(3): Get the GPA of a Student by name." << endl;
cout << "(4): Get names of students based on GPA." << endl;
cout << "(6): Quit the program." << endl;
cout << "Enter your option" << endl;
switch (ch) {
case '1':
cout << "\nEnter student's name" << endl;
cin >> name;
cout << "Enter GPA" << endl;
cin >> GPA;
s[n] = Student(name, GPA);
n++;
break;
case '2':
s[0].printDetails(s, n);
break;
case '3':
cout << "\nEnter the name of a student" << endl;
cin >> name;
GPA = s[0].getGPAbyName(s, n, name);
if (GPA == -1) {
cout << "\nStudent not found!" << endl;
}
else
cout << "\nGPA is: " << endl;
break;
case '4':
cout << "\nEnter GPA: " << endl;
cin >> GPA;
s[0].showListByGPA(s, n, GPA);
break;
case '5':
avg = s[0].calcAverageGPA(s, n);
cout << "\nAverage GPA: " << avg << endl;
break;
case '6':
exit(0);
}
}
I suspect the problem resides in main(). I included the prior blocks of the program in case they were necessary to provide any suggestions.
You obviously want to read in "ch".
You've also made this an int, and don't zero-initialize, which can cause some undefined behaviour if you don't set it beforehand.
The switch case should be
switch(X){
case 1:
// Code
break;
}
etc..
The difference is "1" or 1. It evaluates an enumeration value, instead of strings.
For safety: you might want to add a case default, which is common practice.

Arrays Lose Value Upon Return (Inventory/Menu Program) C++

So for the most part I understand what I did wrong, the issue is I don't know how to fix it.
Goal: This is a store management system that must include a menu and inventory management functions that can be manipulated. To do this I used arrays to add the store's items, their descriptions, and their quantities. All the arrays are partially filled to the third element and have a max value of ten elements.
Issue: When the program is run the first time it works and the user can see their inventory, description and quantity. However when they exit to the menu and come BACK to inventory, everything past the third element is cleared. This is due to the declarations initializing the arrays past the third element to 0. How do I fix this to guarantee the user has their inventory saved and can view it upon return?
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <cmath>
#include <cstdlib>
using namespace std;
//declarations
int mainMenu(); //done
void inventoryMgmt();
void addInv(); //working on
void invView(string x[], int sizeofArray, string y[], int secondArray, int z[], int thirdArray);
void editor(string x[], int sizeofArray, string y[], int secondArray, int z[], int thirdArray);
void customerReciept(); //done
void calculatePrice(); //done
void exit(); //done
const double massTax = 0.0625;
//main
int main() {
int choice;
bool repeat = true;
while (repeat = true) {
choice = mainMenu();
switch (choice) {
case 1:
customerReciept();
break;
case 2:
inventoryMgmt();
break;
//case 3:
//itemSearcher();
//break;
case 4:
exit();
repeat = false;
break;
}
}
return 0;
}
//main menu function ***done
int mainMenu() {
cout << "\n\n\t\t\t\t Welcome to the Massasoit Store Management System " << endl;
cout << "\t\t\t\t ________________________________________________ \n\n";
cout << "\t\t\t\t\t Main Menu: " << endl;
cout << "\t\t\t\t\t\t 1. Customer Reciept" << endl;
cout << "\t\t\t\t\t\t 2. Inventory Management" << endl;
cout << "\t\t\t\t\t\t 3. Item Search" << endl;
cout << "\t\t\t\t\t\t 4. Exit" << endl << endl;
int choice;
cout << "\t\t\t\t\t\t Where do you need to go?: ";
cin >> choice;
while (choice < 1 || choice > 4) {
cout << "\t\t\t\t\t Incorrect Selection Please Select Again: ";
cin >> choice;
}
return choice;
}
//customer reciept function **done
void customerReciept() {
cout << "\n\n\t\t\t\t Welcome to the Massasoit Store: Customer Reciept " << endl;
cout << "\t\t\t\t ________________________________________________ \n\n";
cout << "\t\t\t\t\t Receipt Menu: " << endl;
cout << "\t\t\t\t\t\t 1. Calculate Receipt" << endl;
cout << "\t\t\t\t\t\t 2. Return to Main" << endl;
int recieptChoice;
cout << "\t\t\t\t\t\t Where do you need to go?: ";
cin >> recieptChoice;
while (recieptChoice < 1 || recieptChoice > 2) {
cout << "Invalid Selection Please Choose Again: ";
cin >> recieptChoice;
}
if (recieptChoice == 1) {
calculatePrice();
}
}
void calculatePrice() {
double cost;
double taxAmount;
int numOfItems;
double finalCost = 0;
char tax;
int i;
cout << "\n\n\t\t\t\t Welcome to the Massasoit Store: Customer Reciept " << endl;
cout << "\t\t\t\t ________________________________________________ \n\n";
cout << "How many items were purchased?: ";
cin >> numOfItems;
for (i = 0; i < numOfItems; i++) {
cout << "What did item " << i + 1 << " cost? $";
cin >> cost;
cout << "Is this item taxable? (y/n):";
cin >> tax;
if (tax == 'y' || tax == 'Y') {
taxAmount = (cost * massTax);
cost = taxAmount + cost;
finalCost = cost + finalCost;
}
else {
finalCost = cost + finalCost;
}
}
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout << "This customer's total is $" << finalCost << endl;
}
void inventoryMgmt() {
int invChoice;
cout << "\n\n\t\t\t\t\t Welcome to Inventory Management " << endl;
cout << "\t\t\t\t ______________________________________________ \n\n";
cout << "\t\t\t\t\t Inventory Settings: " << endl;
cout << "\t\t\t\t\t\t 1. Add/View & Edit/Delete Inventory" << endl;
cout << "\t\t\t\t\t\t 2. Return to Main" << endl;
cout << "\t\t\t\t\t\t Where do you need to go?: ";
cin >> invChoice;
cout << endl << endl;
while (invChoice < 1 || invChoice > 2) {
cout << "Invalid Selection Please Choose Again: ";
cin >> invChoice;
}
if (invChoice == 1) {
addInv();
}
if (invChoice == 2) {
//edit/delete();
}
}
void addInv() {
//so when this is called, everything is initialized to 0 which makes it wipe the memory
//when the user comes back to it from the menu.
const int description = 20; //this allows a short description for each item
const int counter = 10; //slots of inventory allowed
int quantity[10] = {10, 15, 45};
string itemArray[counter] = { "Hot Drinks", "Cold Drinks", "Books"};
string descriptionArray[description] = { "Coffee, Tea etc", "Water, juice, etc", "Texts, notebook, etc"};
char addChoice;
int destination;
cout << "\t\t\t\t\t\t 1. Add/View" << endl;
cout << "\t\t\t\t\t\t 2. Edit/Delete" << endl;
cout << "\t\t\t\t\t\t 3. Exit to Main" << endl;
cout << "\t\t\t\t\t\t Where would you like to go?: " << endl;
cin >> destination;
while (destination < 1 || destination > 3) {
cout << "Invalid Selection, Please Select Again: ";
cin >> destination;
}
if (destination == 1) {
cout << "Would you like to add an item? (y/n): ";
cin >> addChoice;
int i = 3; //these two are initialized to three to ensure that the store
int ii = 3; //will always have hot drinks, cold drinks and books as options
while (addChoice == 'y' && i < counter) {
cout << "What would you like to add?: ";
cin >> itemArray[i];
cout << "You have added \"" << itemArray[i] << "\" to the inventory\n";
cout << "Please Provide a Brief Description: ";
cin.ignore();
getline(cin, descriptionArray[ii]);
cout << "You've described \"" << itemArray[i] << "\" as \"" << descriptionArray[i] << "\"" << endl;
cout << "What is the quantity of " << itemArray[i] << " in stock?";
cin >> quantity[i];
cout << "Would you like to add another item?";
cin >> addChoice;
i++;
ii++;
if (i > counter) {
cout << "**INVENTORY LIMIT REACHED*** ";
}
}
invView(itemArray, 10, descriptionArray, 10, quantity, 10); //working on this. //so use this for view, edit, and delete.
}
}
void invView(string x[], int sizeofArray, string y[], int secondArray, int z[], int thirdArray) { //add quantity
int i = 0;
int ii = 0;
int iii = 0;
cout << "Your inventory consists of: ";
while (i < sizeofArray && x[i] != "" && ii < secondArray && y[i] != "" && iii < thirdArray) {
cout << x[i] << " - " << y[i] << " | Quantity: " << z[i] << endl;
i++;
ii++;
}
}
void editor(string x[], int sizeofArray, string y[], int secondArray, int z[], int thirdArray) {
cout << "Which item would you like to edit?";
}
void exit() {
cout << "\n\n\t\t\t\t Welcome to the Massasoit Store Management System " << endl;
cout << "\t\t\t\t ________________________________________________ \n\n";
cout << "\t\t\t\t Thank you for using the Massasoit Store Management System" << endl;
exit(1);
}
I included the entire code in case it was needed. The issues are centered around the inventoryMgmt() and addInv() functions.
Thanks in advance for any help!
In theaddInv() all the arrays are local. Once that function is done executing, all local variables are freed up thus resulting in your deletion. Try place them outside your addInv() function:
int main(){
int quantity[10] = {10, 15, 45};
string itemArray[counter] = { "..."};
string descriptionArray[description] = { "..."};
void addInv() {...}
}

I'm getting a unassigned variable error at the account1 after the GetTransfer. I can not figure out what logic error i have messed up on

Getting an unassigned variable error after the GetTransfer portion of the code. It is claiming account1 is the unassigned variable but from what i can see i have declared it. i have tried multiple times to correct it and i just can figure it out.
#include <iostream>
#include <conio.h>
using namespace std;
// Chance Pinkerton
// December 3, 2013
// CaseProject2Chapter3
struct bankInfo
{
int accountNum;
double startBal;
double endBal;
};
int main()
{
bankInfo account1;
bankInfo account2;
double transferAmt;
int GetAccount1();
int GetAccount2();
double GetBal1();
double GetBal2();
double GetTransfer();
account1.accountNum = GetAccount1();
while (account1.accountNum < 1000 || account1.accountNum > 9999)
{
cout << "Error. That account does not exsist." << endl;
account1.accountNum = GetAccount1();
}
GetBal1();
account2.accountNum = GetAccount2();
while (account2.accountNum < 1000 || account2.accountNum > 9999)
{
cout << "Error. That account number doesnt exsist." << endl;
account2.accountNum = GetAccount2();
}
if (account2.accountNum == account1.accountNum)
{
cout << "Error. Account numbers can not be the same " << endl;
account2.accountNum = GetAccount2();
}
GetBal2();
transferAmt = GetTransfer();
account1.accountNum = (account1.accountNum % 5) + (account1.accountNum * 10);
account2.accountNum = (account2.accountNum % 5) + (account2.accountNum * 10);
account1.endBal;
account2.endBal;
while (account1.endBal < 0)
{
cout << "Error. Account balance can not be negative." << endl;
GetTransfer();
if (account1.endBal < 10)
{
cout << "Warning. Account balance will be below $10.00 " << endl;
}
}
account1.endBal = account1.startBal - transferAmt;
account2.endBal = account2.startBal + transferAmt;
cout << "Account number 1: " << account1.accountNum << endl;
cout << "Starting balance: " << account1.startBal << endl;
cout << "Ending balance: " << account1.endBal << endl;
cout << "Account number 2: " << account2.accountNum << endl;
cout << "Starting balance: " << account2.startBal << endl;
cout << "Ending balance: " << account2.endBal << endl;
getch();
return 0;
}
int GetAccount1()
{
int accountNum;
cout << "Please enter your account number " << endl;
cin >> accountNum;
return accountNum;
}
int GetAccount2()
{
int accountNum;
cout << "Please enter the second account number " << endl;
cin >> accountNum;
return accountNum;
}
double GetBal1()
{
double startBal;
cout << "Enter your account balance " << endl;
cin >> startBal;
return startBal;
}
double GetBal2()
{
double startBal;
cout << "Enter the second account balance " << endl;
cin >> startBal;
return startBal;
}
double GetTransfer()
{
double transferAmt;
cout << "How much would you like to transfer to the second account " << endl;
cin >> transferAmt;
return transferAmt;
}
These two statements do exactly nothing, and are likely the source of the warning the compiler is giving you:
account1.endBal;
account2.endBal;
Furthermore, I think you need to actually capture the return value of GetTransfer() here, perhaps into transferAmt:
GetTransfer();
You probably need to rethink this entire while loop, especially taking into account how transferAmt relates to account1.endBal:
while (account1.endBal < 0)
{
cout << "Error. Account balance can not be negative." << endl;
GetTransfer();
if (account1.endBal < 10)
{
cout << "Warning. Account balance will be below $10.00 " << endl;
}
}
For example, you don't want to update endBal until you know the transfer will succeed. Furthermore, your low-balance warning is in completely the wrong place.

Confused about an exercise in my book

I need to be able to have the objects within the array be valid or invalid/ have value or have no value.
So if the user entered only 5 accounts out of 10 possible, it would throw away the last 5 that do not have any value what so ever, so as to not ask for a computed interest for an account that doesn't exist.
How do I do this?
#include <iostream>
#include <iomanip>
using namespace std;
class BankAccount
{
private:
int accountNum;
double accountBal;
static const double annualIntRate;
public:
void enterAccountData(int, double);
void computeInterest();
void displayAccount();
};
//implementation section:
const double BankAccount::annualIntRate = 0.03;
void BankAccount::enterAccountData(int number, double balance)
{
cout << setprecision(2) << fixed;
cout << "Enter the account number " << endl;
cin >> number;
accountNum = number;
while(number < 0 || number < 1000)
{
cout << "Account numbers cannot be negative or less than 1000 " <<
"Enter a new account number: " << endl;
cin >> number;
}
cout << "Enter the account balance " << endl;
cin >> balance;
accountBal = balance;
while(balance < 0)
{
cout << "Account balances cannot be negative. " <<
"Enter a new account balance: " << endl;
cin >> balance;
}
return;
}
void BankAccount::computeInterest()
{
const int MAX_ACCOUNTS = 10;
const int MONTHS_IN_YEAR = 12;
int months;
double rate = 0;
int counter = 0;
cout << endl << "How many months will the account be held for? " << endl;
cin >> months;
counter = 0;
do
{
accountBal = accountBal * annualIntRate + accountBal;
counter++;
}while(months > counter);
cout << endl << "Account # " << accountNum << " 's balance is:$" << accountBal << endl;
}
int main()
{
const int QUIT = 0;
const int MAX_ACCOUNTS = 10;
int counter;
int input;
int number = 0;
double balance = 0;
BankAccount accounts[MAX_ACCOUNTS];
//BankAccount display;
counter = 0;
do
{
accounts[counter].enterAccountData(number, balance);
cout << " Enter " << QUIT << " to stop, or press 1 to proceed.";
cin >> input;
counter++;
}while(input != QUIT && counter != 10);
for(counter = 0; counter < MAX_ACCOUNTS; counter++)
{
accounts[counter].computeInterest();
}
system("pause");
return 0;
}
You should try tonarrow down your questions to just what you are really asking, this is a little confusing to look at.
After the first loop, have it "remember" what value for counter it managed to reach, and then in the second loop only iterate up to that, instead of up to MAX_ACCOUNTS.
And converting from months to years is just dividing by 12 no?
It seems you have skipped the chapters about Arrays. Re-read it!
ps. surely 0 < 1000 while(number < 0 || number < 1000)
void BankAccount::enterAccountData(int number, double balance). What is the need for the two arguments ? Take the input directly for the member variables. Unnecessary operations are commented. This would also do the job -
void BankAccount::enterAccountData()
{
cout << setprecision(2) << fixed;
cout << "Enter the account number " << endl;
cin >> accountNum; // Take input directly to accountNum
// accountNum = number; // No need of this assignment
while(accountNum < 0 || accountNum < 1000)
{
cout << "Account numbers cannot be negative or less than 1000 " <<
"Enter a new account number: " << endl;
cin >> accountNum;
}
cout << "Enter the account balance " << endl;
cin >> accountBal;
// accountBal = balance; // Unnecessary assignment
while(accountBal < 0)
{
cout << "Account balances cannot be negative. " <<
"Enter a new account balance: " << endl;
cin >> accountBal;
}
// return; // What is the need of this return statement? Method signature says
// it doesn't return anything.
}
When you think of declaring variables, think of whether they are necessary. Unnecessary declaring and assigning the variables make the problem looks complex and is the source of confusion. Think simple :)