Cant create array of objects in c++ - c++

#include <iostream>
using namespace std;
class Bank
{
private:
char account_holder[50];
int accnum;
int balance;
int dep_amount;
int with_amount;
public:
void getdata();
void putdata();
void deposit();
void withdraw();
};
void Bank::getdata()
{
cout << "Enter the account holders name : " << endl;
cin >> account_holder;
cout << "Enter the account number : " << endl;
cin >> accnum;
cout << "Enter the balance in your account : " << endl;
cin >> balance;
}
void Bank::putdata()
{
cout << "The account holders name is : " << account_holder << endl;
cout << "The account number is : " << accnum << endl;
cout << "The balance in your account is : " << balance << endl;
cout << endl;
}
void Bank::deposit()
{
cout << "Enter the amount to be deposited : " << endl;
cin >> dep_amount;
balance = balance + dep_amount;
cout << "Your current balance is : " << balance << endl;
}
void Bank::withdraw()
{
cout << "Enter the amount to be withdrawn : " << endl;
cin >> with_amount;
balance = balance - with_amount;
cout << "Your current balance is : " << balance << endl;
}
int main(){
Bank ram[5];
int ch, a, n, acc;
cout << "How you account holders you want to add : " << endl;
cin >> n;
do
{
cout << "Enter 1.To insert data" << endl;
cout << "Enter 2.To display data" << endl;
cout << "Enter 3.To deposit amount" << endl;
cout << "Enter 4.To withdraw amount" << endl;
cout << "Enter your choice : " << endl;
cin >> ch;
switch (ch)
{
case 1:
for (int i = 0; i < n;i++)
ram[i].getdata();
break;
case 2:
for (int i = 0; i < n; i++)
ram[i].putdata();
break;
case 3:
cout << "Enter the account you want to deposit money into " << endl;
cin >> acc;
for (int i = 0; i < n; i++)
ram[acc].deposit();
break;
case 4:
for (int i = 0; i < n; i++)
ram[i].withdraw();
break;
}
cout << "Enter 6. To Continue" << endl;
cin >> a;
} while (a == 6);
return 0;
}
I am using this code and my problem is that when I want to deposit or withdraw some amount,I want to take account number from user and then deposit/withdraw amount from that object only. How can I enter that object using account number taken from user? Please Help.

Unfortunately you have a few problems with your code and your logic. Let us address them one by one:
1- You are using a char array to keep the account holder name. If you are programming C++ you should be using std::string in almost all situations.
2- You are using unconventional names for your public methods in Bank and this is a bad habit at best.
More specifically, getdata() is a poor method name because mehtods that start with "get" should generally be reserved for methods that return a single field that belongs to the class instance. For example int getAccountNumber()
your getdata() should be fillInData() follow me?
3- You are using an array of Bank in your main in order to hold the number of accounts. While this is possible, it is far from ideal. You should strive to use std::vector when it makes sense (like here). Why is a naked array bad? because if you use an array the size of the array has to be known at compile time, which means you can not increase the number of accounts when the program is running. If you declare a big array on the stack, you may have a lot of space but you are wasting precious stack space.
4- The logic you have employed for your "input loop" is messy and hard to navigate. The design can be improved significantly to improve readability and maintainability of code. Consider the fact that you declare and read int n; but you never use it in the program.
5- Compile time errors from undeclared variables like i
6- Logically and semantically incorrect program behaviour: you iterate through a for loop of all records and withdraw/deposit in ALL records, instead of selecting the one you need.
7- No bounds checking of any kind. Asking for bad things to happen.
I am giving you a minimally adjusted code that makes sense. Note that this is still not the ideal way to accomplish this task but at least it does not have syntax and semantic errors:
int Bank::getAccountNumber()
{
return this->accnum;
}
int getIndexByAccountNumber(Bank allAccounts[], int size, int accountNumber) //returns index or -1 in case account number is not found
{
for(int i=0; i<size; ++i)
{
if (allAccounts[i].getAccountNumber()==accountNumber) return i;
}
return -1;
}
int main(){
const int NumberOfAccounts=5;
Bank ram[NumberOfAccounts];
int nextIndex=0;
int ch, a, acc;
while(true)
{
cout << "Enter 1.To insert data for a new account" << endl;
cout << "Enter 2.To display data of all existing accounts" << endl;
cout << "Enter 3.To deposit to an existing account" << endl;
cout << "Enter 4.To withdraw from an existing account" << endl;
cout << "Enter 5.To terminate program" << endl;
cout << "Enter your choice : " << endl;
cin >> ch;
if(ch==1)
{
if(nextIndex>=NumberOfAccounts)
{
cout<<"error: you have space for only "<<NumberOfAccounts<<" accounts! terminating program";
break;//breaks out of while loop
}
ram[nextIndex].getdata();//gets all fields for the account
nextIndex++;
}
else if(ch==2)
{
cout << "showing information for all accounts: " << endl;
for (int i = 0; i < nextIndex; i++) ram[i].putdata();
cout<<"\n\n";
}
else if(ch==3)
{
cout << "Enter the account you want to deposit money into " << endl;
cin >> acc;
int index = getIndexByAccountNumber(ram,NumberOfAccounts,acc);
if(index==-1)
{
cout<<"the account number you entered could not be found, terminating program!\n";
break;//breaks out of while loop
}
ram[index].deposit();
}
else if(ch==4)
{
cout << "Enter the account you want to withdraw from " << endl;
cin >> acc;
int index= getIndexByAccountNumber(ram,NumberOfAccounts,acc);
if(index==-1)
{
cout<<"the account number you entered could not be found, terminating program!\n";
break;//breaks out of while loop
}
ram[index].withdraw();
}
else if(ch==5)
{
break;
}
else
{
cout<<"you entered invalid choice\n";
}
}//end of while loop
return 0;
}

cout << "Enter the account you want to deposit money into " << endl;
cin >> acc;
for (int i = 0; i < n; i++)
ram[acc].deposit();
break;
Here is your problem - wrong index variable. Try "i"

In your case 3 you use a different iterator than the rest. Is this by design or what? I am missing the purpose of using acc instead of i. This might be your problem, unless I am overlooking your purpose for using it.

Related

C++ Banking application not holding more than one account

Hello I've been working on a C++ banking application that should be able to hold more than one account with all the related field's. I have come across a few issues:
When displaying account info in Display or ShowInfo functions, the first letter of the first name and the middle initial wont show up.
When creating an account only the most recent account is able to be searched for and displayed in display data. I know that an array is needed for this to be possible, I'm just not sure if implemented this correctly.
Thanks for the help. Any input is appreciated!
#include <stdlib.h>
#include <conio.h>
#include <iostream>
#include <string>
using namespace std;
class BankAccount{
double Balance = 0.0;
char ans;
public:struct Name{
char Last_Name[50];
char First_Name[50];
char Middle_Initial[5];
}Name;
public:struct Account{
char Type[1];
int Account_Number;
}Account;
public:
void CreateAccount();
void Withdraw();
void Deposit();
void Display();
void ShowInfo();
int Menu();
};
void BankAccount::CreateAccount(){
do
{
cout << "\nEnter account number: ";
cin >> Account.Account_Number;
cout << "\nEnter the last name for the account: ";
cin.ignore();
cin.getline(Name.Last_Name, 50);
cout << "\nEnter the first name for the account: ";
cin.ignore();
cin.getline(Name.First_Name, 50);
cout << "\nEnter the Middle initial for the account: ";
cin.ignore();
cin.getline(Name.Middle_Initial, 5);
cout << "\nEnter the type of account (C/S) : ";
cin >> Account.Type;
cout << "\nEnter the initial balance of the account: ";
cin >> Balance;
cout << "\n\nAccount Created.";
cout << "\n\nCreate new account? (Y/N) : ";
cin >> ans;
while (ans != 'Y' && ans != 'N'){
cout << "Invalid input. Create new account? (Y/N) : ";
cin >> ans;
}
cout << endl;
} while (ans != 'N');
};
void BankAccount::Withdraw(){
int actNum;
double amount;
cout << "Enter the account number for the account that you wish to withdraw funds: ";
cin >> actNum;
if (actNum == Account.Account_Number){
cout << "Enter the amount you would like to withdraw: ";
cin >> amount;
Balance = Balance - amount;
}
else if (actNum != Account.Account_Number){
cout << "No account found under that number! Try again!";
}
}
void BankAccount::Deposit(){
int actNum;
double amount;
cout << "Enter the account number for the account that you wish to deposit funds: ";
cin >> actNum;
if (actNum == Account.Account_Number){
cout << "Enter the amount you would like to deposit: ";
cin >> amount;
Balance = Balance + amount;
}
else if (actNum != Account.Account_Number){
cout << "No account found under that number! Try again!";
}
}
void BankAccount::Display(){
int actNum;
cout << "Enter the account number for the account that you wish to display account information for: ";
cin >> actNum;
if (actNum == Account.Account_Number){
cout << "Account details for " << Name.First_Name << " " << Name.Middle_Initial << " " << Name.Last_Name << "'s account: " << endl;
cout << "Account Number: " << Account.Account_Number << endl;
cout << "Account Type (Checking / Savings): " << Account.Type << endl;
cout << "Account Balance: $" << Balance << endl;
}
else if (actNum != Account.Account_Number){
cout << "No account found under that number! Try again!";
}
}
void BankAccount::ShowInfo(){
cout << "Account details for " << Name.First_Name << " " << Name.Middle_Initial << " " << Name.Last_Name << "'s account: " << endl;
cout << "Account Number: " << Account.Account_Number << endl;
cout << "Account Type (Checking / Savings): " << Account.Type << endl;
cout << "Account Balance: $" << Balance << endl;
}
int main(int argc, char *argv){
BankAccount ob;
char ch;
cout << "Welcome to Console Banking Application V 1.0!";
cout << "\nSelect an item from the list below by entering the corresponding letter.";
do{
cout << "\n\n A. Create Account \n B. Withdraw \n C. Deposit \n D. Show Account Details \n\n Q. Exit Application\n\n";
ch = ob.Menu();
switch (ch){
case 'A':
case 'a': ob.CreateAccount();
ob.ShowInfo();
break;
case 'B':
case 'b': ob.Withdraw();
break;
case 'C':
case 'c': ob.Deposit();
break;
case 'D':
case 'd': ob.Display();
break;
case 'Q':
case 'q': ob.ShowInfo();
exit(1);
break;
}
} while (1);
}
int BankAccount::Menu(){
char ch;
cout << "Select an option: ";
cin >> ch;
return ch;
}
The simple answer is: You only have one bank account.
If you look at your main function, you create one, and only one BankAccount. As you would probably guess, one BankAccount cannot be used to represent multiple BankAccounts(SoAs aside).
Therefore, you need an array of BankAccounts. It goes something like this:
BankAccount obs[10];
Now you have 10 BankAccounts, no more. So every time you want to create a new BankAccount, just make sure that you create it on a BankAccount in the array that is not currently in use.
obs[0].CreateAccount();
obs[0].ShowInfo();
obs[0].Deposit();
//Make a new account
obs[1].CreateAccount();
...
To go even further, let's consider the fact that you have 10 BankAccounts, and only 10. This is not very extensive now is it? What's a bank with only 10 accounts available? Probably out of business in due time.
The naive solution would be to just add more. 50, 100, even 1000. But do you really want to go back and update that number every single time? That's way too tedious.
Fortunately, there's a convenient container we can use:
#include <vector>
...
std::vector<BankAccount> obs;
...
This is basically an array that expands itself automatically when required. I will not go into detail on how to use vectors because I am sure that you can easily learn to do so yourself. I will, however, leave you with this link so you know where you can start.

array based database not working correctly

I have to write a program for an array based database that will allow the user to enter new data, update existing data, delete entries and view a list of the entries. The requirements are a structure called DATE, a structure called CustData that holds the user data, an array of type CustData with a size of 10 and requires an individual function for entering, updating, deleting and displaying the customer data. It also needs to use a while loop to initialize each index in the array with everything initialized to 0. I have a rough program written but the more I work on it the more I feel like I am doing it completely wrong. So far I have it working to the point that it lets me add multiple entries without overwriting previous ones, but I can't seem to be able to limit the number of entries I can input. I also have the displaying of entries correct. Any help that could be offered is greatly appreciated, below is my program so far, with some of the data input sections commented out to make testing it easier. My apologies for leaving this out, this is in C++, written with visual studio 2013.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
struct Date
{
int month,
day,
year;
};
struct cust
{
int ID;
string name;
string address;
string city;
string state;
string zip;
string phone;
double balance;
Date lastpayment;
};
const int SIZE = 10;
int menuchoice;
int num = 0;
int i;
void showmenu();
void funcentercustdata(cust[], int);
void funcupdatecustdata();
void funcdeletecustdata();
void funcdisplaycustdata(cust[], int);
cust custdb[SIZE];
int main()
{
cout << "Welcome to Michael's Marvelous Database Contrabulator!\n";
cout << setw(10) << "Customer Database\n\n\n";
showmenu();
int index;
for (index = 0; index < SIZE; index++)
{
custdb[index].ID = 0;
custdb[index].name = "";
custdb[index].address = "";
custdb[index].city = "";
custdb[index].state = "";
custdb[index].zip = "";
custdb[index].phone = "";
custdb[index].balance = 0.00;
custdb[index].lastpayment.month = 0;
custdb[index].lastpayment.day = 0;
custdb[index].lastpayment.year = 0;
}
return 0;
}
void showmenu()
{
cout << "\n\n1) Enter new customer data.\n";
cout << "2) Update customer data.\n";
cout << "3) Delete customer data.\n";
cout << "4) Display Customer data.\n";
cout << "5) Quit the program.\n\n";
cout << "Please enter your choice: ";
cin >> menuchoice;
do
{
switch (menuchoice)
{
case 1:
funcentercustdata(custdb, SIZE);
showmenu();
break;
case 2:
funcupdatecustdata();
showmenu();
break;
case 3:
funcdeletecustdata();
showmenu();
break;
case 4:
funcdisplaycustdata(custdb, SIZE);
showmenu();
break;
case 5:
cout << "Thank you and have a nice day!\n";
break;
default:
cout << "Please enter a correct choice\n";
cin >> menuchoice;
break;
}
} while (menuchoice != 5);
}
void funcentercustdata(cust custinfo[], int size)
{
if (custinfo[i].ID != 0)
{
i++;
cout << "\n\nEnter ID: ";
cin >> custinfo[i].ID;
cout << "Enter name: ";
cin.ignore(0);
cin >> custinfo[i].name;
/* cout << "Enter address: ";
cin.ignore(0);
cin>>custinfo[i].address;
cout << "Enter city: ";
cin.ignore(0);
cin>>custinfo[i].city;
cout << "Enter state: ";
cin.ignore(0);
cin>>custinfo[i].state;
cout << "Enter zip: ";
cin.ignore(0);
cin>>custinfo[i].zip;
cout << "Enter phone number (###-###-####): ";
cin.ignore(0);
cin>>custinfo[i].phone;
cout << "Enter balance: ";
cin >> custinfo[i].balance;
cout << "Enter last payment (mo day year, e.g. 11 17 2014): ";
cin >> custinfo[i].lastpayment.month >> custinfo[i].lastpayment.day
>> custinfo[i].lastpayment.year;
cin.ignore(1);
// }*/
cout << "Customers successfully added.\n";
}
else if (custinfo[i].ID != 0 && custinfo[i].ID >= 4)
{
cout << "No further inputs allowed\n";
}
else
{
cout << "\n\nEnter ID: ";
cin >> custinfo[i].ID;
cout << "Enter name: ";
cin.ignore(0);
cin >> custinfo[i].name;
/* cout << "Enter address: ";
cin.ignore(0);
cin>>custinfo[i].address;
cout << "Enter city: ";
cin.ignore(0);
cin>>custinfo[i].city;
cout << "Enter state: ";
cin.ignore(0);
cin>>custinfo[i].state;
cout << "Enter zip: ";
cin.ignore(0);
cin>>custinfo[i].zip;
cout << "Enter phone number (###-###-####): ";
cin.ignore(0);
cin>>custinfo[i].phone;
cout << "Enter balance: ";
cin >> custinfo[i].balance;
cout << "Enter last payment (mo day year, e.g. 11 17 2014): ";
cin >> custinfo[i].lastpayment.month >> custinfo[i].lastpayment.day
>> custinfo[i].lastpayment.year;
cin.ignore(1);
// }*/
cout << "Customers successfully added.\n";
}
}
void funcupdatecustdata()
{
cout << "insert function 2\n\n";
}
void funcdeletecustdata()
{
cout << "insert function 3\n\n";
}
void funcdisplaycustdata(cust custinfo[], int size)
{
for (int i = 0; i < size; i++)
{
if (custinfo[i].ID == 0)
cout << " ";
else if (custinfo[i].ID != 0)
{
cout << "\n\nClient ID: " << custinfo[i].ID << endl;
cout << "Client name: " << custinfo[i].name << endl;
/* cout << "Client address: " << custinfo[i].name << endl;
cout << "Client city: " << custinfo[i].name << endl;
cout << "Client state: " << custinfo[i].name << endl;
cout << "Client zip: " << custinfo[i].name << endl;
cout << "Client phone: " << custinfo[i].name << endl;*/
cout << "Client balance: " << custinfo[i].balance << endl;
cout << "Client last deposit: " << custinfo[i].lastpayment.month << "/" <<
custinfo[i].lastpayment.day << "/" << custinfo[i].lastpayment.year << endl;
}
}
}
You've asked multiple questions concerning the issues in your program. So I will look at the first question:
I can't seem to be able to limit the number of entries I can input
First, your code has some fundamental flaws. One flaw is the repeated calling of showmenu() while you're in the showmenu() function. This is a recursive call, and is totally unnecessary. Imagine if your program or similar program that was structured this way had to be running 24 hours a day, and there were thousands of entries added. You will evenutally blow out the stack with all the recursive calls. So this has to be fixed.
Second, showmenu(), at least to me, should do what it says, and that is "show the menu". It should not be processing input. Do the processing of input in a separate function.
Here is a more modularized version of the program:
#include <iostream>
void processChoice(int theChoice);
void showmenu();
void addCustomer();
void deleteCustomer();
int getMenuChoice();
int customerCount = 0;
int main()
{
cout << "Welcome to Michael's Marvelous Database Contrabulator!\n";
cout << setw(10) << "Customer Database\n\n\n";
int choice = 0;
do
{
showmenu();
choice = getMenuChoice();
if (choice != 5)
processChoice(choice);
} while (choice != 5);
}
void showmenu()
{
cout << "\n\n1) Enter new customer data.\n";
cout << "2) Update customer data.\n";
cout << "3) Delete customer data.\n";
cout << "4) Display Customer data.\n";
cout << "5) Quit the program.\n\n";
}
int getMenuChoice()
{
int theChoice;
cout << "Please enter your choice: ";
cin >> theChoice;
return theChoice;
}
void processChoice(int theChoice)
{
switch (theChoice)
{
case 1:
addCustomer();
break;
//...
case 3:
deleteCustomer();
break;
}
}
void addCustomer()
{
if ( customerCount < 10 )
{
// add customer
// put your code here to add the customer
//...
// increment the count
++customerCount;
}
}
void deleteCustomer()
{
if ( customerCount > 0 )
{
// delete customer
--customerCount;
}
}
This is the basic outline of keeping track of the number of customers. Code organization and modularity is the key. The count of the current number of entries is either incremented or decremented wihin the addCustomer and deleteCustomer functions. Also note the test that is done in add/deleteCustomer().
In the main() function, note the do-while loop and the way it is set up. The showMenu function shows itself, the getMenuChoice function gets the choice and returns the number that was chosen.
If the choice is not 5, process the request. If it is 5, then the while part of the do-while kicks you out of the processing, otherwise you start back at the top (showMenu, getMenuChoice, etc). This avoids the recursive calls that your original code was doing.

Cannot figure out how to do this code

I have been working on this project that simulates a bank account. The user can deposit, withdraw, and have all the withdraws and deposits displayed on the screen. At the top of the selection menu needs to be the current balance. Like so, SAVINGS : 100. And whenever I deposit money or withdraw money I need that balance to change to the correct amount. The amount starts at $100. If I deposit or withdraw money it will work perfectly the first time, but on the second time it gets reset back to $100 and then the transaction is done. How can I make the balance stay the correct amount without it resetting? This is a school project and I am not looking for someone to provide me the code. I am just seeking some tips or guidance in the right direction. Here is the code for my int main() :
int main ()
{
saving sa;
creditCard cca;
checking ca;
string n;
int option;
int exit = 1;
int x = 1;
do{
cout << endl;
cout << "Checking Balance:" << ca.getBalance() << " " << "Savings balance:" << sa.getBalance() << " " << "Credit Card balance:" << cca.getBalance() << endl;
cout << endl;
cout << " (1) Savings Deposit " << endl;
cout << " (2) Savings withdrawel " << endl;
cout << " (3) Checking Deposit " << endl;
cout << " (4) Write A Check " << endl;
cout << " (5) Credit Card Payment " << endl;
cout << " (6) Make A Charge " << endl;
cout << " (7) Display Savings " << endl;
cout << " (8) Display Checkings " << endl;
cout << " (9) Display Credit Card " << endl;
cout << " (0) Exit " << endl;
cin >> option;
switch ( option )
{
case 1 : {
double SamtD;
cout << " Please enter how much you would like to deposit into savings " << endl;
cin >> SamtD;
sa.makeDeposit(SamtD);
break;
};
case 2 : {
int SamtW;
cout << " Please enter how much you would like to withdraw "<< endl;
cin >> SamtW;
sa.doWithdraw(SamtW);
break;
}
case 3 : {
double CamtD;
cout << " Please enter how much you would like to deposit into checkings " << endl;
cin >> CamtD;
ca.makeDeposit(CamtD);
break;
}
case 4 : {
double CamtW;
int chkNum;
cout << " Please enter how much you wrote on the check " << endl;
cin >> CamtW;
cout << " Please enter the check number " << endl;
cin >> chkNum;
ca.writeCheck(chkNum, CamtW);
break;
}
case 5 : {
double CCmkP;
cout << " Please enter the amount you would like to deposit " << endl;
cin >> CCmkP;
cca.makePayment(CCmkP);
break;
}
case 6 : {
double DoC;
string Nm;
cout << " Please enter the amount charged to your credit card " << endl;
cin >> DoC;
cout << " Please enter where the charge was made " << endl;
cin >> Nm;
getline(cin, Nm);
cca.doCharge(Nm,DoC);
break;
}
case 7 : {
sa.display();
break;
}
case 8 : {
ca.display();
break;
}
case 9 : {
cca.display();
break;
}
case 0 : exit = 0;
break;
default : exit = 0;
cout << " ERROR ";
}
}
while(exit==1);
return 0;
}
and here is were the balance is being set :
double curbalance = 100;
void account::setBalanceD(double balance) // This is for deposit
{
itsBalance = balance;
}
void account::setBalanceW(double balance) // This is for withdraw
{
double newBalance = curBalance - balance;
itsBalance = newBalance;
}
double account::getBalance()
{
return itsBalance;
}
and here is the code that option 2 in my menu would be calling :
int saving:: doWithdraw(int amount)
{
if (amount > 0)
{
for (int i = 9; i != 0; i--)
{
last10withdraws[i] = last10withdraws[i-1];
}
last10withdraws[0] = amount;
setBalanceW(amount);
}
else
{
cout << " ERROR. Number must be greater then zero. " << endl;
}
return 0;
}
Any ideas? I just cannot get the balance to remain accurate.
The problem is that your setBalanceW() function never deducts from curBalance, so it stays at 100.
void account::setBalanceW(double balance) // This is for withdraw
{
curBalance -= balance;
}
Your other references should be to curBalance as well, as there should only be one current balance.
void account::setBalanceD(double balance) // This is for deposit
{
curBalance += balance;
}
double account::getBalance()
{
return curBalance;
}
The best solution, though (presuming that itsBalance is a member of the account class, would be to eliminate curBalance altogether, and just open your main() with an initial deposit:
int main ()
{
saving sa;
creditCard cca;
checking ca;
sa.makeDeposit(100.0);
/* other code */
}
/* Note no curBalance variable? */
void account::setBalanceW(double balance) // This is for withdraw
{
itsBalance -= balance;
}
void account::setBalanceD(double balance) // This is for deposit
{
itsBalance += balance;
}
double account::getBalance()
{
return itsBalance;
}
Your implementation for performing a deposit appears to be incorrect. It should be:
void account::setBalanceD(double balance) // This is for deposit
{
itsBalance += balance;
}
Notice that we are now adding the amount being deposited to the current balance, instead of explicitly setting it's value. Similarly as Ken pointed out the same applies to performing a withdraw.
void account::setBalanceW(double balance) // This is for withdraw
{
itsBalance -= balance;
}

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 :)

C++ 2d Array Class Function Call Help

I hope this question takes a simple fix, and I am just missing something very small.
I am in my second semester of C++ in college, and we are just getting into OOP. This is my first OOP program, and it is causing me a little problem. Here are the errors I am getting:
Member function must be called or its address taken in function displayGrid(int,Cell ( *)[20])
Member function must be called or its address taken in function Turn(int,int,Cell ( *)[20])
Member function must be called or its address taken in function Turn(int,int,Cell ( *)[20])
Warning: Parameter 'grid' is never used in function displayGrid(int,Cell ( *)[20])
Here is all of my code. I am aware It is much more code than necessary, sorry if it makes it more difficult. I was worried that I might accidentally delete something.
const int MAX=20;
//Struct Cell holds player and their symbol.
class Cell
{
private:
int Player;
char Symbol;
public:
Cell(void);
void setPlayer(int);
void setSymbol(char);
int getPlayer(void);
char getSymbol(void);
};
Cell::Cell(void)
{
Symbol ='-';
}
void Cell::setPlayer(int player_num)
{
Player = player_num;
}
void Cell::setSymbol(char rps)
{
Symbol = rps;
}
int Cell::getPlayer(void)
{
return Player;
}
char Cell::getSymbol(void)
{
return Symbol;
}
void Turn(int, int, Cell[MAX][MAX]);
void displayGrid(int, Cell[MAX][MAX]);
void main(void)
{
int size;
cout << "How big would you like the grid to be: ";
cin >> size;
//Checks to see valid grid size
while(size>MAX || size<3)
{
cout << "Grid size must between 20 and 3." << endl;
cout << "Please re-enter the grid size: ";
cin >> size;
}
int cnt=1;
int full;
Cell grid[MAX][MAX];
//I use full to detect when the game is over by squaring size.
full = size*size;
cout << "Starting a new game." << endl;
//Exits loop when cnt reaches full.
while(cnt<full+1)
{
displayGrid(size, grid); //calls function to display grid
if(cnt%2==0) //if cnt is even then it's 2nd players turn
cout << "Player 2's turn." << endl;
else
cout << "Player 1's turn" << endl;
Turn(size, cnt, grid); //calls Turn do each players turn
cnt++;
}
cout << endl;
cout << "Board is full... Game Over" << endl;
}
void displayGrid(int size, Cell grid[MAX][MAX])
{
cout << endl;
cout << " ";
for(int x=1; x<size+1; x++) // prints first row
cout << setw(3) << x; // of numbers.
cout << endl;
//Nested-For prints the grid.
for(int i=1; i<size+1; i++)
{
cout << setw(2) << i;
for(int c=1; c<size+1; c++)
{
cout << setw(3) << grid[i][c].getSymbol;
}
cout << endl;
}
cout << endl;
}
void Turn(int size, int cnt, Cell grid[MAX][MAX])
{
char temp;
char choice;
int row=0;
int column=0;
cout << "Enter the Row: ";
cin >> row;
cout << "Enter the Column: ";
cin >> column;
//puts what is in the current cell in "temp"
temp = grid[row][column].getSymbol;
//Checks to see if temp is occupied or not
while(temp!='-')
{
cout << "Cell space is Occupied..." << endl;
cout << "Enter the Row: ";
cin >> row;
cout << "Enter the Column: ";
cin >> column;
temp = grid[row][column].getSymbol; //exits loop when finally correct
}
if(cnt%2==0) //if cnt is even then its player 2's turn
{
cout << "Enter your Symbol R, P, or S (Capitals): ";
cin >> choice;
grid[row][column].setPlayer(1);
in >> choice;
}
//officially sets choice to grid cell
grid[row][column].setSymbol(choice);
}
else //if cnt is odd then its player 1's turn
{
cout << "Enter your Symbol r, p, or s (Lower-Case): ";
cin >> choice;
grid[row][column].setPlayer(2);
//checks for valid input by user1
while(choice!= 'r' && choice!='p' && choice!='s')
{
cout << "Invalid Symbol... Please Re-Enter: ";
cin >> choice;
}
//officially sets choice to grid cell.
grid[row][column].setSymbol(choice);
}
cout << endl;
}
Thanks alot for your help!
The following line:
cout << setw(3) << grid[i][c].getSymbol;
Doesn't call the function. Write this instead:
cout << setw(3) << grid[i][c].getSymbol();
Likewise for the other error messages.
The warning is generated because the erroneous line is the only time displayGrid uses the grid parameter.
You forgot the function parens:
cout << setw(3) << grid[i][c].getSymbol;
should be:
cout << setw(3) << grid[i][c].getSymbol();