C++/c++

Advertisement


Question
QUESTION: could u pls help mi.i realli realli need alot of help frm u.i still cn't seems to do the interest earn and gain/loss.
for tis program,One customer can have more than one bank accounts and investment accounts,associated by customerID.hw should i do so tat the customer will hv 2 accounts and investment.below is the final result tat i should gt.i will be so greatly appericated for all the help frm u.

result:
*** Individual Customer Statistics ***
*** Customer Particulars ***
Customer ID: 10001
Name: Mickey Mouse
Address: Sengkang
Phone: 91111111
Customer Type: Gold

*** Bank accounts ***
Number: 700001
Type: Savings
Original Balance: $10000.00
Num of years: 2
Interest earned: $500.00
Final Balance: $10500.00

Number: 800001
Type: Checkings
Original Balance: $20000.00
Num of years: 3
Interest earned: $900.00
Final Balance: $20900.00

*** Investment accounts ***
Number: 3300001
Type: Stock
Invested value: $10000.00
Current value: $12000.00
Gain/ Loss: $2000.00

Number: 8800001
Type: RealEstate
Invested value: $100000.00
Current value: $120000.00
Gain/ Loss: $20000.00

code:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <sstream>
#include <vector>

using namespace std;


class Customer
{
public:
  enum CustomerType
  {
      Normal = 1,
      Gold,
      Silver,
      Platinum
  };

  Customer(){};
  void setCustomer(int, string, string, string, int, CustomerType);
  void display();
  bool read(ifstream& fin);
  CustomerType getType(void)const{return type;}
  int getId(void)const{ return customerID;}

private:
  int customerID;
  string firstName;
  string lastName;
  string address;
  int phoneNum;
  CustomerType type;
  

  static const int ID_LENGTH = 5;
  static const int PHONE_LENGTH = 8;
};

class Account
{
public:
  enum AccountType
  {
      Savings = 1,
      Checkings,
      FixedDeposit
  };

  Account () {}
  void setAccount(int, int, AccountType, int, int);
  void display();
  bool read(ifstream& fin);
  void addInterest();
  

private:
  int customerID;
  int accountNum;
  int balance;
  int numYears;
  int finalBalance;
  int earn;
  AccountType type;

  static const int ID_LENGTH = 5;
  static const int ACCOUNT_LENGTH = 6;
};

class Investment
{
public:
  enum InvestmentType
  {
      Stock = 1,
      RealEstate
  };

  Investment () {}
  void setInvestment(int, int, InvestmentType, int, int);
  void display();
  bool read(ifstream& fin);
  void Value();

private:
  int customerID;
  int investNum;
  int investValue;
  int currValue;
  int gain_loss;
  InvestmentType type;
    

  static const int ID_LENGTH = 5;
  static const int INVESTNUM_LENGTH = 7;

};

//vectors to hold customers, accounts, and investments
vector<Customer> customers;
vector<Account> accounts;
vector<Investment> investments;

void Customer::setCustomer(int id, string fn, string ln, string add, int pn, CustomerType ct)
{
  customerID = id;
  firstName = fn;
  lastName = ln;
  address = add;
  phoneNum = pn;
  type = ct;
}

void Customer::display()
{
 
  cout << endl;
  cout << "================================================================================";
  cout << "*** Individual Customer Statistics ***" << endl;
  cout << "*** Customer Particulars ***" << endl;
  cout << "CustomerID: " << customerID << ' ' << "\nName: " << firstName << "  " <<  lastName << "  "
       << "\nAddress: " << address << " " << "\nPhone: " << phoneNum << " " << "\nCustomer Type: " << type << endl;   
  
  switch(type)
 {
  case Normal:   cout << "Normal\n";
         break;
  case Gold:     cout << "Gold\n";
         break ;
  case Silver:   cout << "Silver\n";
         break;
  case Platinum: cout << "Platinum\n";
         break;
  default:       cout << "invalid value\n";
 }
    
}

bool allDigits(const string& input)
{
  for(size_t ix = 0; ix < input.size(); ++ix)
  {
      if (!isdigit(input[ix])) return false;
  }
  return true;
}

void toLowerCase(string& input)
{
  for(size_t ix = 0; ix < input.size(); ++ix) input[ix] = tolower(input[ix]);
}

bool Customer::read(ifstream& fin)
{
  // First read individual strings from the file
  string idText;
  string firstNameText;
  string lastNameText;
  string addressText;
  string phoneText;
  string typeText;


  // Read the entire line in.
  string line;
  getline(fin, line);
  istringstream ss (line);
  ss >> idText >> firstNameText >> lastNameText >> addressText >> phoneText >> typeText;


  // Now check that each input is valid

  // Check ID
  if (idText.length() != ID_LENGTH || !allDigits(idText)) return false;

  // Check names
  if (firstNameText.length() == 0) return false;
  if (lastNameText.length() == 0) return false;

  // Check address
  if (addressText.length() == 0) return false;

  // Check phone
  if (phoneText.length() != PHONE_LENGTH || !allDigits(phoneText)) return false;

  // Check customer type
  CustomerType inputType;
  toLowerCase(typeText);
  if(typeText == "normal")inputType = Normal;
  else if (typeText =="gold")inputType = Gold;
  else if (typeText == "silver")inputType = Silver;
  else if (typeText == "platinum")inputType = Platinum;
  else return false;

  // Now assign all inputs to the customer
  setCustomer(atoi(idText.c_str()),
      firstNameText,
      lastNameText,
      addressText,
      atoi(phoneText.c_str()),
      inputType);
  return true;
}

void Account::setAccount(int id, int an, AccountType at, int bl, int ny)
{
  customerID = id;
  accountNum = an;
  balance = bl;
  numYears = ny;
  type = at;
  earn=0;
  finalBalance=balance;   
}

void Account::display()
{
  cout << endl;
  cout << "================================================================================";
  cout << "*** Bank accounts ***" << endl;
  cout << "Number: " << accountNum << "\nType: " << type  
       << "\nOriginal Balance: " << "$" << balance << "\nNumber of Years: " << numYears << "\nInterest Earned: "
     << "$" << earn << "\nFinal Balance: " << "$" << finalBalance << endl;
  
  switch(type)
 {
  case Savings:       cout << "Savings\n";
         break;
  case Checkings:     cout << "Checkings\n";
         break;
  case FixedDeposit:  cout << "FixedDeposit\n";
         break;
  default:          cout << "invalid value\n";
 }   
}

void Account::addInterest()
{
 
  double interestRate;

  // Set the normal interest rate
  switch(type)
  {
  case Savings:
       interestRate = 1.5;
       break;
  case Checkings:
       interestRate = 1.0;
       break;
  case FixedDeposit:
       interestRate = 2.0;
       break;
  }

  // Add bonuses for account type and customer type
  switch(type)
  {
  case Customer::Silver:
      switch(type)
      {
      case Savings:
         interestRate += 0.5;
         break;
      case Checkings:
         interestRate += 0.25;
         break;
      case FixedDeposit:
         interestRate += 1.0;
         break;
      }
      break;
  case Customer::Gold:
      switch(type)
      {
      case Savings:
         interestRate += 1.0;
         break;
      case Checkings:
         interestRate += 0.5;
         break;
      case FixedDeposit:
         interestRate += 2.0;
         break;
      }
      break;
  case Customer::Platinum:
      switch(type)
      {
      case Savings:
         interestRate += 1.5;
         break;
      case Checkings:
         interestRate += 0.75;
         break;
      case FixedDeposit:
         interestRate += 3.0;
         break;
      }
      break;
  }

  finalBalance = balance;

  earn = 0;
  int year;

  for(int year = 1; year <= this->numYears; ++year)
  {
      
      double interest = finalBalance * (interestRate/100);
     finalBalance =  earn + interest;
  }
}

bool is_positive_double(const string& str)
{
  istringstream ch(str);
  double d = -1.0;

  // try to read a double from the stream
  if( ch >> d )
  {
      char remaining;
      // if there are more chars left
      if( ch >> remaining ) return false;

      else return d > 0.0; // no more chars, success if number read is positive
  }

  return false ; // read of double failed
}

bool Account::read(ifstream& fin)
{
  // First read individual data from the file
  string idText;
  string accountNumText;
  string typeText;
  string balanceText;
  string numYearsText;


  // Read the entire line in.
  string line;
  getline(fin, line);
  istringstream ss (line);
  ss >> idText >> accountNumText >> typeText >> balanceText >> numYearsText;


  // Now check that each input is valid

  // Check ID
  if (idText.length() != ID_LENGTH || !allDigits(idText)) return false;

  // Check AccountNum
  if (accountNumText.length() != ACCOUNT_LENGTH || !allDigits(accountNumText)) return false;

  // Check account type
  AccountType inputType;
  toLowerCase(typeText);
  if (typeText == "savings")inputType = Savings;
  else if (typeText == "checkings")inputType = Checkings;
  else if (typeText == "fixeddeposit")inputType = FixedDeposit;
  else return false;
  
  // Check balance
  if(!is_positive_double(balanceText)) return false;

  // Check years
  if (numYearsText.length() == 0) return false;

  // Now assign all inputs to the account
  setAccount(atoi(idText.c_str()),
      atoi(accountNumText.c_str()),
      inputType,
      atoi(balanceText.c_str()),
      atoi(numYearsText.c_str()));
  return true;
}

void Investment::setInvestment(int id, int in, InvestmentType it, int iv, int cv)
{
  customerID = id;
  investNum = in;
  investValue = iv;
  currValue = cv;
  type = it;
  gain_loss=gain_loss;
}

void Investment::display()
{
  cout << endl;
  cout << "================================================================================";
  cout << "*** Investments ***" << endl;
  cout << "Number: " << investNum << "\nType: " << type << "\nInvested Value: " << "$" << investValue
     << "\nCurrent Value: " << "$" << currValue << "\nGain/Loss: " << "$" << gain_loss << endl;
  
  switch(type)
 {
  case Stock:         cout << "Stock\n";
         break;
  case RealEstate:    cout << "RealEstate\n";
         break;
  default:          cout << "invalid value\n";
 }
}

void Investment::Value()
{

  // Set the normal
  switch(type)
  {
  case Stock:
       break;
  case RealEstate:
       break;
  }

  //customer type and invest type
  switch(type)
  {
  case Customer::Silver:
      switch(type)
      {
      case Stock:
       break;
  case RealEstate:
       break;
      }
      break;
  case Customer::Gold:
      switch(type)
      {
      case Stock:
       break;
  case RealEstate:
       break;
      }
      break;
  case Customer::Platinum:
      switch(type)
      {
      case Stock:
       break;
  case RealEstate:
       break;
      }
      break;
  }
}

bool characters(const string& str )
{
  istringstream ch(str);
  double d = -1.0;

  // try to read a double from the stream
  if( ch >> d )
  {
      char remaining;
      // if there are more chars left
      if( ch >> remaining ) return false;

      else return d > 0.0; // no more chars, success if number read is positive
  }

  return false ; // read of double failed
}

bool Investment::read(ifstream& fin)
{
  // First read individual data from the file
  string idText;
  string investNumText;
  string typeText;
  string investValueText;
  string currValueText;
  

  // Read the entire line in.
  string line;
  getline(fin, line);
  istringstream ss (line);
  ss >> idText >> investNumText >> typeText >> investValueText >> currValueText;


  // Now check that each input is valid

  // Check ID
  if (idText.length() != ID_LENGTH || !allDigits(idText)) return false;

  // Check AccountNum
  if (investNumText.length() != INVESTNUM_LENGTH || !allDigits(investNumText)) return false;

  // Check account type
  InvestmentType inputType;
  toLowerCase(typeText);
  if (typeText =="stock")inputType = Stock;
  else if (typeText == "realestate")inputType =  RealEstate;
  else return false;

  // Check invest value
  if(!characters(investValueText)) return false;

  // Check current value
  if (currValueText.length() == 0) return false;

  // Now assign all inputs to the investment
  setInvestment(atoi(idText.c_str()),
      atoi(investNumText.c_str()),
      inputType,
      atoi(investValueText.c_str()),
      atoi(currValueText.c_str()));
  return true;
}
  
int main()
{          
  ////////////////////////////////////////////////////////
  // Open files
  ////////////////////////////////////////////////////////

  ifstream customerFile("customers.txt");
  ifstream accountFile("account.txt");
  ifstream investmentFile("investment.txt");

  if (!customerFile.is_open())
  {
      cout << "Error opening customer file";
      exit (1);
  }

  if (!accountFile.is_open())
  {
      cout << "Error opening accounts file";
      exit (1);
  }

  if (!investmentFile.is_open())
  {
      cout << "Error opening investments file";
      exit (1);
  }
  
  
  ////////////////////////////////////////////////////////
  // Read in files
  ////////////////////////////////////////////////////////

  Customer c;
  while (!customerFile.eof())
  {
      if (c.read(customerFile)) customers.push_back(c);
  }
  
  Account a;
  while (!accountFile.eof())
  {
      if (a.read(accountFile)) accounts.push_back(a);
  }
  
  Investment i;
  while (!investmentFile.eof())
  {
      if (i.read(investmentFile)) investments.push_back(i);
  }
  
  ////////////////////////////////////////////////////////
  // Print out overall statistics
  ////////////////////////////////////////////////////////
  int gold = 0;
  int platinum = 0;
  int silver = 0;
  int normal = 0;
  int type = 0;
  for (size_t i = 0; i < customers.size(); ++i)
  {
      switch(customers[i].getType())
      {
        case Customer::Normal: ++normal;
         break;
      case Customer::Silver: ++silver;
         break;
       case Customer::Gold: ++gold;
         break;
        case Customer::Platinum: ++platinum;
         break;
      }
  }
  
  type = normal+silver+gold+platinum;
  
  cout << "================================================================================";
  cout << "*** Overall Customer Statistics ***" << endl;
  cout << "Number of customers type Normal: " << normal << endl;
  cout << "Number of customers type Silver: " << silver << endl;
  cout << "Number of customers type Gold: " << gold << endl;
  cout << "Number of customers type Platinim: " << platinum << endl;
  cout << "Total number of customers: " << type << endl;
  cout << endl;
         
  ////////////////////////////////////////////////////////
  // Print out customers,account and investment
  ////////////////////////////////////////////////////////
  for(int i = 0; i < customers.size(); ++i)
  {
        customers[i].display();
     accounts[i].display();
     investments[i].display();
         accounts[i].addInterest();
  }
  
  system("pause");
  return 0;
}





ANSWER: Lisa, where you have

  ////////////////////////////////////////////////////////
   // Print out customers,account and investment
   ////////////////////////////////////////////////////////
   for(int i = 0; i < customers.size(); ++i)
   {
       customers[i].display();
       accounts[i].display();
       investments[i].display();
       accounts[i].addInterest();
   }

You have a problem. The i counter is goes from 0 to the number of customers. The accounts, and investments vectors are not the same size as the customers vector. For example, you may have 10 customers, but only 3 investments. When you try to access investment[4], the program will have an error. You need a separate loop for the other vectors.

The code should look like this:
   ////////////////////////////////////////////////////////
   // Print out customers,account and investment
   ////////////////////////////////////////////////////////
   for(int i = 0; i < customers.size(); ++i)
   {
       customers[i].display();
   }
   for (int i = 0; i < accounts.size(); ++i)
   {
       accounts[i].addInterest();
       accounts[i].display();
   }
   for (int i = 0; i < investments.size(); ++i)
   {
       investments[i].display();
   }

Lisa, the Account::addInterest code you sent me is incorrect. The code I sent you in my last post was almost correct. Actually it was correct, but the answer you expect in your assignment is wrong.  $10000 over 2 years at 2.5% per year should give 10506, not 10500, however, Ive changed the code to give the answer you want. In a real bank, you get $10000 *1.025 = $10250 at the end of the first year. At the end of the second year you get $10250 * 1.025  = 10506.25.

Now, lets get to the investment code.
In  your program you have
void Investment::setInvestment(int id, int in, InvestmentType it, int iv, int cv)
{
   customerID = id;
   investNum = in;
   investValue = iv;
   currValue = cv;
   type = it;
   gain_loss=gain_loss;
}
Please tell me what you are trying to do in the last line of that function.

All you need to do now is calculate the gain or loss. You can do so when you are printing out the investment, or you can do so in the
void Investment::setInvestment
method.

How do you calculate the gain or loss ? It is the value now minus the value you started out with. Take the code I am sending you and add the gain or loss calculation. Then, after a little bit of formatting, you will have the output you want. Use your computer to copy and paste the code into your program file. Don't just try to type it from the screen.

Kindest regards
Zlatko.

CODE
===================================
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <sstream>
#include <vector>

using namespace std;


class Customer
{
public:
   enum CustomerType
   {
       Normal = 1,
       Gold,
       Silver,
       Platinum
   };

   Customer(){};
   void setCustomer(int, string, string, string, int, CustomerType);
   void display();
   bool read(ifstream& fin);
   CustomerType getType(void)const{return type;}
   int getId(void)const{ return customerID;}

private:
   int customerID;
   string firstName;
   string lastName;
   string address;
   int phoneNum;
   CustomerType type;


   static const int ID_LENGTH = 5;
   static const int PHONE_LENGTH = 8;
};

class Account
{
public:
   enum AccountType
   {
       Savings = 1,
       Checkings,
       FixedDeposit
   };

   Account () {}
   void setAccount(int, int, AccountType, int, int);
   void display();
   bool read(ifstream& fin);
   void addInterest();


private:
   int customerID;
   int accountNum;
   int balance;
   int numYears;
   int finalBalance;
   int earn;
   AccountType type;

   static const int ID_LENGTH = 5;
   static const int ACCOUNT_LENGTH = 6;
};

class Investment
{
public:
   enum InvestmentType
   {
       Stock = 1,
       RealEstate
   };

   Investment () {}
   void setInvestment(int, int, InvestmentType, int, int);
   void display();
   bool read(ifstream& fin);
   void Value();

private:
   int customerID;
   int investNum;
   int investValue;
   int currValue;
   int gain_loss;
   InvestmentType type;


   static const int ID_LENGTH = 5;
   static const int INVESTNUM_LENGTH = 7;

};

//vectors to hold customers, accounts, and investments
vector<Customer> customers;
vector<Account> accounts;
vector<Investment> investments;

// NEW
// getCustomerType returns the customer type for a given customer ID
Customer::CustomerType getCustomerType(int customerId)
{
  for (size_t i = 0; i < customers.size(); ++i)
  {
      if (customers[i].getId() == customerId) return customers[i].getType();
  }
  cout << "Error: customer " << customerId << " was not found\n";
  return Customer::Normal;
}

void Customer::setCustomer(int id, string fn, string ln, string add, int pn, CustomerType ct)
{
   customerID = id;
   firstName = fn;
   lastName = ln;
   address = add;
   phoneNum = pn;
   type = ct;
}

void Customer::display()
{

   cout << endl;
   cout << "================================================================================";
   cout << "*** Individual Customer Statistics ***" << endl;
   cout << "*** Customer Particulars ***" << endl;
   cout << "CustomerID: " << customerID << ' ' << "\nName: " << firstName << "  " <<  lastName << "  "
       << "\nAddress: " << address << " " << "\nPhone: " << phoneNum << " " << "\nCustomer Type: " << type << endl;   

   switch(type)
   {
   case Normal:   cout << "Normal\n";
       break;
   case Gold:     cout << "Gold\n";
       break ;
   case Silver:   cout << "Silver\n";
       break;
   case Platinum: cout << "Platinum\n";
       break;
   default:       cout << "invalid value\n";
   }

}

bool allDigits(const string& input)
{
   for(size_t ix = 0; ix < input.size(); ++ix)
   {
       if (!isdigit(input[ix])) return false;
   }
   return true;
}

void toLowerCase(string& input)
{
   for(size_t ix = 0; ix < input.size(); ++ix) input[ix] = tolower(input[ix]);
}

bool Customer::read(ifstream& fin)
{
   // First read individual strings from the file
   string idText;
   string firstNameText;
   string lastNameText;
   string addressText;
   string phoneText;
   string typeText;


   // Read the entire line in.
   string line;
   getline(fin, line);
   istringstream ss (line);
   ss >> idText >> firstNameText >> lastNameText >> addressText >> phoneText >> typeText;


   // Now check that each input is valid

   // Check ID
   if (idText.length() != ID_LENGTH || !allDigits(idText)) return false;

   // Check names
   if (firstNameText.length() == 0) return false;
   if (lastNameText.length() == 0) return false;

   // Check address
   if (addressText.length() == 0) return false;

   // Check phone
   if (phoneText.length() != PHONE_LENGTH || !allDigits(phoneText)) return false;

   // Check customer type
   CustomerType inputType;
   toLowerCase(typeText);
   if(typeText == "normal")inputType = Normal;
   else if (typeText =="gold")inputType = Gold;
   else if (typeText == "silver")inputType = Silver;
   else if (typeText == "platinum")inputType = Platinum;
   else return false;

   // Now assign all inputs to the customer
   setCustomer(atoi(idText.c_str()),
       firstNameText,
       lastNameText,
       addressText,
       atoi(phoneText.c_str()),
       inputType);
   return true;
}

void Account::setAccount(int id, int an, AccountType at, int bl, int ny)
{
   customerID = id;
   accountNum = an;
   balance = bl;
   numYears = ny;
   type = at;
   earn=0;
   finalBalance=balance;   
}

void Account::display()
{
   cout << endl;
   cout << "================================================================================";
   cout << "*** Bank accounts ***" << endl;
   cout << "Number: " << accountNum << "\nType: " << type  
       << "\nOriginal Balance: " << "$" << balance << "\nNumber of Years: " << numYears << "\nInterest Earned: "
       << "$" << earn << "\nFinal Balance: " << "$" << finalBalance << endl;

   switch(type)
   {
   case Savings:       cout << "Savings\n";
       break;
   case Checkings:     cout << "Checkings\n";
       break;
   case FixedDeposit:  cout << "FixedDeposit\n";
       break;
   default:          cout << "invalid value\n";
   }   
}

void Account::addInterest(void)
{
  Customer::CustomerType customerType = getCustomerType(customerID);
  float interestRate;

  // Set the normal interest rate
  switch(type)
  {
  case Savings:
      interestRate = 1.5;
      break;
  case Checkings:
      interestRate = 1.0;
      break;
  case FixedDeposit:
      interestRate = 2.0;
      break;
  }

  // Add bonuses for account type and customer type
  switch(customerType)
  {
  case Customer::Silver:
      switch(type)
      {
      case Savings:
         interestRate += 0.5;
         break;
      case Checkings:
         interestRate += 0.25;
         break;
      case FixedDeposit:
         interestRate += 1.0;
         break;
      }
      break;
  case Customer::Gold:
      switch(type)
      {
      case Savings:
         interestRate += 1.0;
         break;
      case Checkings:
         interestRate += 0.5;
         break;
      case FixedDeposit:
         interestRate += 2.0;
         break;
      }
      break;
  case Customer::Platinum:
      switch(type)
      {
      case Savings:
         interestRate += 1.5;
         break;
      case Checkings:
         interestRate += 0.75;
         break;
      case FixedDeposit:
         interestRate += 3.0;
         break;
      }
      break;
  }

  finalBalance = balance;
  earn = 0;
  for(int year = 1; year <= this->numYears; ++year)
  {
      float interest = finalBalance * (interestRate / 100);
      earn += interest;
  }
  finalBalance += earn;
}

bool is_positive_double(const string& str)
{
   istringstream ch(str);
   double d = -1.0;

   // try to read a double from the stream
   if( ch >> d )
   {
       char remaining;
       // if there are more chars left
       if( ch >> remaining ) return false;

       else return d > 0.0; // no more chars, success if number read is positive
   }

   return false ; // read of double failed
}

bool Account::read(ifstream& fin)
{
   // First read individual data from the file
   string idText;
   string accountNumText;
   string typeText;
   string balanceText;
   string numYearsText;


   // Read the entire line in.
   string line;
   getline(fin, line);
   istringstream ss (line);
   ss >> idText >> accountNumText >> typeText >> balanceText >> numYearsText;


   // Now check that each input is valid

   // Check ID
   if (idText.length() != ID_LENGTH || !allDigits(idText)) return false;

   // Check AccountNum
   if (accountNumText.length() != ACCOUNT_LENGTH || !allDigits(accountNumText)) return false;

   // Check account type
   AccountType inputType;
   toLowerCase(typeText);
   if (typeText == "savings")inputType = Savings;
   else if (typeText == "checkings")inputType = Checkings;
   else if (typeText == "fixeddeposit")inputType = FixedDeposit;
   else return false;

   // Check balance
   if(!is_positive_double(balanceText)) return false;

   // Check years
   if (numYearsText.length() == 0) return false;

   // Now assign all inputs to the account
   setAccount(atoi(idText.c_str()),
       atoi(accountNumText.c_str()),
       inputType,
       atoi(balanceText.c_str()),
       atoi(numYearsText.c_str()));
   return true;
}

void Investment::setInvestment(int id, int in, InvestmentType it, int iv, int cv)
{
   customerID = id;
   investNum = in;
   investValue = iv;
   currValue = cv;
   type = it;

   /////////////////////////////////////////////////////////////////
   /*
       calculate gain_loss right here
       What is it?
       It is the value now minus the value you started with
   */
   gain_loss=gain_loss;
}

void Investment::display()
{
   cout << endl;
   cout << "================================================================================";
   cout << "*** Investments ***" << endl;
   cout << "Number: " << investNum << "\nType: " << type << "\nInvested Value: " << "$" << investValue
       << "\nCurrent Value: " << "$" << currValue << "\nGain/Loss: " << "$" << gain_loss << endl;

   switch(type)
   {
   case Stock:         cout << "Stock\n";
       break;
   case RealEstate:    cout << "RealEstate\n";
       break;
   default:          cout << "invalid value\n";
   }
}

void Investment::Value()
{

   // Set the normal
   switch(type)
   {
   case Stock:
       break;
   case RealEstate:
       break;
   }

   //customer type and invest type
   switch(type)
   {
   case Customer::Silver:
       switch(type)
       {
       case Stock:
         break;
       case RealEstate:
         break;
       }
       break;
   case Customer::Gold:
       switch(type)
       {
       case Stock:
         break;
       case RealEstate:
         break;
       }
       break;
   case Customer::Platinum:
       switch(type)
       {
       case Stock:
         break;
       case RealEstate:
         break;
       }
       break;
   }
}

bool characters(const string& str )
{
   istringstream ch(str);
   double d = -1.0;

   // try to read a double from the stream
   if( ch >> d )
   {
       char remaining;
       // if there are more chars left
       if( ch >> remaining ) return false;

       else return d > 0.0; // no more chars, success if number read is positive
   }

   return false ; // read of double failed
}

bool Investment::read(ifstream& fin)
{
   // First read individual data from the file
   string idText;
   string investNumText;
   string typeText;
   string investValueText;
   string currValueText;


   // Read the entire line in.
   string line;
   getline(fin, line);
   istringstream ss (line);
   ss >> idText >> investNumText >> typeText >> investValueText >> currValueText;


   // Now check that each input is valid

   // Check ID
   if (idText.length() != ID_LENGTH || !allDigits(idText)) return false;

   // Check AccountNum
   if (investNumText.length() != INVESTNUM_LENGTH || !allDigits(investNumText)) return false;

   // Check account type
   InvestmentType inputType;
   toLowerCase(typeText);
   if (typeText =="stock")inputType = Stock;
   else if (typeText == "realestate")inputType =  RealEstate;
   else return false;

   // Check invest value
   if(!characters(investValueText)) return false;

   // Check current value
   if (currValueText.length() == 0) return false;

   // Now assign all inputs to the investment
   setInvestment(atoi(idText.c_str()),
       atoi(investNumText.c_str()),
       inputType,
       atoi(investValueText.c_str()),
       atoi(currValueText.c_str()));
   return true;
}

int main()
{          
   ////////////////////////////////////////////////////////
   // Open files
   ////////////////////////////////////////////////////////

   ifstream customerFile("customers.txt");
   ifstream accountFile("account.txt");
   ifstream investmentFile("investment.txt");

   if (!customerFile.is_open())
   {
       cout << "Error opening customer file";
       exit (1);
   }

   if (!accountFile.is_open())
   {
       cout << "Error opening accounts file";
       exit (1);
   }

   if (!investmentFile.is_open())
   {
       cout << "Error opening investments file";
       exit (1);
   }


   ////////////////////////////////////////////////////////
   // Read in files
   ////////////////////////////////////////////////////////

   Customer c;
   while (!customerFile.eof())
   {
       if (c.read(customerFile)) customers.push_back(c);
   }

   Account a;
   while (!accountFile.eof())
   {
       if (a.read(accountFile)) accounts.push_back(a);
   }

   Investment i;
   while (!investmentFile.eof())
   {
       if (i.read(investmentFile)) investments.push_back(i);
   }

   ////////////////////////////////////////////////////////
   // Print out overall statistics
   ////////////////////////////////////////////////////////
   int gold = 0;
   int platinum = 0;
   int silver = 0;
   int normal = 0;
   int type = 0;
   for (size_t i = 0; i < customers.size(); ++i)
   {
       switch(customers[i].getType())
       {
       case Customer::Normal: ++normal;
         break;
       case Customer::Silver: ++silver;
         break;
       case Customer::Gold: ++gold;
         break;
       case Customer::Platinum: ++platinum;
         break;
       }
   }

   type = normal+silver+gold+platinum;

   cout << "================================================================================";
   cout << "*** Overall Customer Statistics ***" << endl;
   cout << "Number of customers type Normal: " << normal << endl;
   cout << "Number of customers type Silver: " << silver << endl;
   cout << "Number of customers type Gold: " << gold << endl;
   cout << "Number of customers type Platinim: " << platinum << endl;
   cout << "Total number of customers: " << type << endl;
   cout << endl;

   ////////////////////////////////////////////////////////
   // Print out customers,account and investment
   ////////////////////////////////////////////////////////
   for(int i = 0; i < customers.size(); ++i)
   {
       customers[i].display();
   }
   for (int i = 0; i < accounts.size(); ++i)
   {
       accounts[i].addInterest();
       accounts[i].display();
   }
   for (int i = 0; i < investments.size(); ++i)
   {
       investments[i].display();
   }

   system("pause");
   return 0;
}


---------- FOLLOW-UP ----------

QUESTION: thankz veri much for guiding mi for the whole process.i am so greatly appericated for all the help u give mi.i hv done the calculation,everything is ok.below is the result tat i should gt,but it did nt display in tis way at all.as we cn c tat the first customer hv 2 accounts and investments.i hv to make it to display in tat way.could u also pls guide mi on the display summary of customer.i realli gt no idea on displaying out the whole thing,and i hv to display it in ascending order.

the result tat i should gt:
*** Individual Customer Statistics ***       
*** Customer Particulars ***      
Customer ID: 10001      
Name: Mickey Mouse      
Address: Sengkang      
Phone: 91111111      
Customer Type: Gold      
     
*** Bank accounts ***      
Number: 700001      
Type: Savings      
Original Balance: $10000.00      
Num of years: 2      
Interest earned: $500.00       
Final Balance: $10500.00      
     
Number: 800001      
Type: Checkings      
Original Balance: $20000.00      
Num of years: 3      
Interest earned: $900.00      
Final Balance: $20900.00      
     
*** Investment accounts ***      
Number: 3300001      
Type: Stock      
Invested value: $10000.00      
Current value: $12000.00      
Gain/ Loss: $2000.00      
     
Number: 8800001      
Type: RealEstate      
Invested value: $100000.00      
Current value: $120000.00      
Gain/ Loss: $20000.00

      
output://wrong
================================================================================
*** Individual Customer Statistics ***
*** Customer Particulars ***
CustomerID: 10001
Name: Mickey  Mouse
Address: Sengkang
Phone: 91111111
Customer Type: 2
Gold

================================================================================
*** Individual Customer Statistics ***
*** Customer Particulars ***
CustomerID: 50020
Name: Humpty  Dumpty
Address: JurongWest
Phone: 94444444
Customer Type: 1
Normal

================================================================================
*** Bank accounts ***
Number: 700001
Type: 1
Original Balance: $10000
Number of Years: 2
Interest Earned: $500
Final Balance: $10500
Savings

================================================================================
*** Bank accounts ***
Number: 800001
Type: 2
Original Balance: $20000
Number of Years: 3
Interest Earned: $900
Final Balance: $20900
Checkings

================================================================================
*** Investments ***
Number: 3300001
Type: 1
Invested Value: $10000
Current Value: $12000
Gain/Loss: $2000
Stock

================================================================================
*** Investments ***
Number: 8800001
Type: 2
Invested Value: $100000
Current Value: $120000
Gain/Loss: $20000
RealEstate



ANSWER: Hello Lisa.

If I understand correctly, for each customer, you have to print out the accounts and investments before moving on to the next customer.

I suggest these changes.

Create a loop to do the interest calculation before going to do the display section.

Like this:

   ////////////////////////////////////////////////////////
   //Add interest
   ////////////////////////////////////////////////////////
   for (int acc = 0; acc < accounts.size(); ++acc)
   {
         accounts[acc].addInterest();
   }
   ////////////////////////////////////////////////////////
   // Print out customers,account and investment
   ////////////////////////////////////////////////////////


Now for the display.
What you need is a loop to go through each customer and display the current customer. You already have that. Then INSIDE the customer loop you need another loop to go through all the accounts. For each account, if the account customerID is the same as the current customer's customerID, then print out that account.

When that account loop is DONE, you need a third loop for investments. The investment loop should be after the account loop but INSIDE the customer loop. It needs to follow the same idea as the account loop. For each investment, if the investment customerID is the same as the current customers's customerID, then print out the investment.

You will need to add a getCustomerId method to the account and investment class so that you can get the customerId for them.

Each loop should have its own counter that shows what vector the counter is indexing. For example, look at the above loop to add interest. I changed the counter from a simple 'i' to 'acc' to show that it is used to go through the account vector.

Compile your file often as you are making your changes. Compile it whenever you complete a logical structure, like a loop. In that way you will not be overwhelmed by a huge number of compiler error messages at the end. You now have enough code examples to handle this section. You need to work on it without panicking. Show me your changes and I will give you a quick function to sort the accounts and investments vectors so that they come out in ascending order.

Best regards.
Zlatko

---------- FOLLOW-UP ----------

QUESTION: thankz for your great help.i hv done the changes.but wen i compile,there is still something wrong with the display.i think my for loop did nt do it correctly.

code:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <sstream>
#include <vector>

using namespace std;


class Customer
{
public:
  enum CustomerType
  {
      Normal = 1,
      Gold,
      Silver,
      Platinum
  };

  Customer(){}
  void setCustomer(int, string, string, string, int, CustomerType);
  void display();
  bool read(ifstream& fin);
  CustomerType getType(void)const{return type;}
  int getId(void)const{ return customerID;}

private:
  int customerID;
  string firstName;
  string lastName;
  string address;
  int phoneNum;
  CustomerType type;


  static const int ID_LENGTH = 5;
  static const int PHONE_LENGTH = 8;
};

class Account
{
public:
  enum AccountType
  {
      Savings = 1,
      Checkings,
      FixedDeposit
  };

  Account () {}
  void setAccount(int, int, AccountType, int, int);
  void display();
  bool read(ifstream& fin);
  void addInterest();
  int getId(void)const{ return customerID;}//ADDED

private:
  int customerID;
  int accountNum;
  int balance;
  int numYears;
  int finalBalance;
  int earn;
  AccountType type;

  static const int ID_LENGTH = 5;
  static const int ACCOUNT_LENGTH = 6;
};

class Investment
{
public:
  enum InvestmentType
  {
      Stock = 1,
      RealEstate
  };

  Investment () {}
  void setInvestment(int, int, InvestmentType, int, int);
  void display();
  bool read(ifstream& fin);
  int getId(void)const{ return customerID;}//ADDED

private:
  int customerID;
  int investNum;
  int investValue;
  int currValue;
  int gain_loss;
  InvestmentType type;


  static const int ID_LENGTH = 5;
  static const int INVESTNUM_LENGTH = 7;

};

//vectors to hold customers, accounts, and investments
vector<Customer> customers;
vector<Account> accounts;
vector<Investment> investments;


// getCustomerType returns the customer type for a given customer ID
Customer::CustomerType getCustomerType(int customerId)
{
 for (size_t i = 0; i < customers.size(); ++i)
 {
     if (customers[i].getId() == customerId) return customers[i].getType();
 }
 cout << "Error: customer " << customerId << " was not found
";
 return Customer::Normal;
}

void Customer::setCustomer(int id, string fn, string ln, string add, int pn, CustomerType ct)
{
  customerID = id;
  firstName = fn;
  lastName = ln;
  address = add;
  phoneNum = pn;
  type = ct;
}

void Customer::display()
{

  cout << endl;
  cout << "================================================================================";
  cout << "*** Individual Customer Statistics ***" << endl;
  cout << "*** Customer Particulars ***" << endl;
  cout << "CustomerID: " << customerID << ' ' << "
Name: " << firstName << "  " <<  lastName << "  "
      << "
Address: " << address << " " << "
Phone: " << phoneNum << " " << "
Customer Type: " << type << endl;   

  switch(type)
  {
  case Normal:   cout << "Normal
";
      break;
  case Gold:     cout << "Gold
";
      break ;
  case Silver:   cout << "Silver
";
      break;
  case Platinum: cout << "Platinum
";
      break;
  default:       cout << "invalid value
";
  }

}

bool allDigits(const string& input)
{
  for(size_t ix = 0; ix < input.size(); ++ix)
  {
      if (!isdigit(input[ix])) return false;
  }
  return true;
}

void toLowerCase(string& input)
{
  for(size_t ix = 0; ix < input.size(); ++ix) input[ix] = tolower(input[ix]);
}

bool Customer::read(ifstream& fin)
{
  // First read individual strings from the file
  string idText;
  string firstNameText;
  string lastNameText;
  string addressText;
  string phoneText;
  string typeText;


  // Read the entire line in.
  string line;
  getline(fin, line);
  istringstream ss (line);
  ss >> idText >> firstNameText >> lastNameText >> addressText >> phoneText >> typeText;


  // Now check that each input is valid

  // Check ID
  if (idText.length() != ID_LENGTH || !allDigits(idText)) return false;

  // Check names
  if (firstNameText.length() == 0) return false;
  if (lastNameText.length() == 0) return false;

  // Check address
  if (addressText.length() == 0) return false;

  // Check phone
  if (phoneText.length() != PHONE_LENGTH || !allDigits(phoneText)) return false;

  // Check customer type
  CustomerType inputType;
  toLowerCase(typeText);
  if(typeText == "normal")inputType = Normal;
  else if (typeText =="gold")inputType = Gold;
  else if (typeText == "silver")inputType = Silver;
  else if (typeText == "platinum")inputType = Platinum;
  else return false;

  // Now assign all inputs to the customer
  setCustomer(atoi(idText.c_str()),
      firstNameText,
      lastNameText,
      addressText,
      atoi(phoneText.c_str()),
      inputType);
  return true;
}

void Account::setAccount(int id, int an, AccountType at, int bl, int ny)
{
  customerID = id;
  accountNum = an;
  balance = bl;
  numYears = ny;
  type = at;
  earn=0;
  finalBalance=balance;   
}

void Account::display()
{
  cout << endl;
  cout << "================================================================================";
  cout << "*** Bank accounts ***" << endl;
  cout << "Number: " << accountNum << "
Type: " << type  
      << "
Original Balance: " << "$" << balance << "
Number of Years: " << numYears << "
Interest Earned: "
      << "$" << earn << "
Final Balance: " << "$" << finalBalance << endl;

  switch(type)
  {
  case Savings:       cout << "Savings
";
      break;
  case Checkings:     cout << "Checkings
";
      break;
  case FixedDeposit:  cout << "FixedDeposit
";
      break;
  default:          cout << "invalid value
";
  }   
}

void Account::addInterest(void)
{
 Customer::CustomerType customerType = getCustomerType(customerID);
 float interestRate;

 // Set the normal interest rate
 switch(type)
 {
 case Savings:
     interestRate = 1.5;
     break;
 case Checkings:
     interestRate = 1.0;
     break;
 case FixedDeposit:
     interestRate = 2.0;
     break;
 }

 // Add bonuses for account type and customer type
 switch(customerType)
 {
 case Customer::Silver:
     switch(type)
     {
     case Savings:
         interestRate += 0.5;
         break;
     case Checkings:
         interestRate += 0.25;
         break;
     case FixedDeposit:
         interestRate += 1.0;
         break;
     }
     break;
 case Customer::Gold:
     switch(type)
     {
     case Savings:
         interestRate += 1.0;
         break;
     case Checkings:
         interestRate += 0.5;
         break;
     case FixedDeposit:
         interestRate += 2.0;
         break;
     }
     break;
 case Customer::Platinum:
     switch(type)
     {
     case Savings:
         interestRate += 1.5;
         break;
     case Checkings:
         interestRate += 0.75;
         break;
     case FixedDeposit:
         interestRate += 3.0;
         break;
     }
     break;
 }

 finalBalance = balance;
 earn = 0;
 for(int year = 1; year <= this->numYears; ++year)
 {
     float interest = finalBalance * (interestRate / 100);
     earn += interest;
 }
     finalBalance += earn;
}

bool is_positive_double(const string& str)
{
  istringstream ch(str);
  double d = -1.0;

  // try to read a double from the stream
  if( ch >> d )
  {
      char remaining;
      // if there are more chars left
      if( ch >> remaining ) return false;

      else return d > 0.0; // no more chars, success if number read is positive
  }

  return false ; // read of double failed
}

bool Account::read(ifstream& fin)
{
  // First read individual data from the file
  string idText;
  string accountNumText;
  string typeText;
  string balanceText;
  string numYearsText;


  // Read the entire line in.
  string line;
  getline(fin, line);
  istringstream ss (line);
  ss >> idText >> accountNumText >> typeText >> balanceText >> numYearsText;


  // Now check that each input is valid

  // Check ID
  if (idText.length() != ID_LENGTH || !allDigits(idText)) return false;

  // Check AccountNum
  if (accountNumText.length() != ACCOUNT_LENGTH || !allDigits(accountNumText)) return false;

  // Check account type
  AccountType inputType;
  toLowerCase(typeText);
  if (typeText == "savings")inputType = Savings;
  else if (typeText == "checkings")inputType = Checkings;
  else if (typeText == "fixeddeposit")inputType = FixedDeposit;
  else return false;

  // Check balance
  if(!is_positive_double(balanceText)) return false;

  // Check years
  if (numYearsText.length() == 0) return false;

  // Now assign all inputs to the account
  setAccount(atoi(idText.c_str()),
      atoi(accountNumText.c_str()),
      inputType,
      atoi(balanceText.c_str()),
      atoi(numYearsText.c_str()));
  return true;
}

void Investment::setInvestment(int id, int in, InvestmentType it, int iv, int cv)
{
  customerID = id;
  investNum = in;
  investValue = iv;
  currValue = cv;
  type = it;

  gain_loss=gain_loss;
  
  gain_loss = currValue-investValue;
}

void Investment::display()
{
  cout << endl;
  cout << "================================================================================";
  cout << "*** Investments ***" << endl;
  cout << "Number: " << investNum << "
Type: " << type << "
Invested Value: " << "$" << investValue
       << "
Current Value: " << "$" << currValue << "
Gain/Loss: " << "$" << gain_loss << endl;

  switch(type)
  {
  case Stock:         cout << "Stock
";
      break;
  case RealEstate:    cout << "RealEstate
";
      break;
  default:          cout << "invalid value
";
  }
}


bool characters(const string& str )
{
  istringstream ch(str);
  double d = -1.0;

  // try to read a double from the stream
  if( ch >> d )
  {
      char remaining;
      // if there are more chars left
      if( ch >> remaining ) return false;

      else return d > 0.0; // no more chars, success if number read is positive
  }

  return false ; // read of double failed
}

bool Investment::read(ifstream& fin)
{
  // First read individual data from the file
  string idText;
  string investNumText;
  string typeText;
  string investValueText;
  string currValueText;


  // Read the entire line in.
  string line;
  getline(fin, line);
  istringstream ss (line);
  ss >> idText >> investNumText >> typeText >> investValueText >> currValueText;


  // Now check that each input is valid

  // Check ID
  if (idText.length() != ID_LENGTH || !allDigits(idText)) return false;

  // Check InvestmentNum
  if (investNumText.length() != INVESTNUM_LENGTH || !allDigits(investNumText)) return false;

  // Check investment type
  InvestmentType inputType;
  toLowerCase(typeText);
  if (typeText =="stock")inputType = Stock;
  else if (typeText == "realestate")inputType =  RealEstate;
  else return false;

  // Check invest value
  if(!characters(investValueText)) return false;

  // Check current value
  if (currValueText.length() == 0) return false;

  // Now assign all inputs to the investment
  setInvestment(atoi(idText.c_str()),
      atoi(investNumText.c_str()),
      inputType,
      atoi(investValueText.c_str()),
      atoi(currValueText.c_str()));
  return true;
}

int main()
{          
  ////////////////////////////////////////////////////////
  // Open files
  ////////////////////////////////////////////////////////

  ifstream customerFile("customers.txt");
  ifstream accountFile("account.txt");
  ifstream investmentFile("investment.txt");

  if (!customerFile.is_open())
  {
      cout << "Error opening customer file";
      exit (1);
  }

  if (!accountFile.is_open())
  {
      cout << "Error opening accounts file";
      exit (1);
  }

  if (!investmentFile.is_open())
  {
      cout << "Error opening investments file";
      exit (1);
  }


  ////////////////////////////////////////////////////////
  // Read in files
  ////////////////////////////////////////////////////////

  Customer c;
  while (!customerFile.eof())
  {
      if (c.read(customerFile)) customers.push_back(c);
  }

  Account a;
  while (!accountFile.eof())
  {
      if (a.read(accountFile)) accounts.push_back(a);
  }

  Investment i;
  while (!investmentFile.eof())
  {
      if (i.read(investmentFile)) investments.push_back(i);
  }

  ////////////////////////////////////////////////////////
  // Print out overall statistics
  ////////////////////////////////////////////////////////
  int gold = 0;
  int platinum = 0;
  int silver = 0;
  int normal = 0;
  int type = 0;
  for (size_t i = 0; i < customers.size(); ++i)
  {
      switch(customers[i].getType())
      {
      case Customer::Normal: ++normal;
         break;
      case Customer::Silver: ++silver;
         break;
      case Customer::Gold: ++gold;
         break;
      case Customer::Platinum: ++platinum;
         break;
      }
  }

  type = normal+silver+gold+platinum;

  cout << "================================================================================";
  cout << "*** Overall Customer Statistics ***" << endl;
  cout << "Number of customers type Normal: " << normal << endl;
  cout << "Number of customers type Silver: " << silver << endl;
  cout << "Number of customers type Gold: " << gold << endl;
  cout << "Number of customers type Platinim: " << platinum << endl;
  cout << "Total number of customers: " << type << endl;

   
  //CHANGES  
  ////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////
  // Print out customers,account and investment
  
  for(int i = 0; i < customers.size(); ++i)
  {
    customers[i].display();
    for(int acc = 0; acc < accounts.size(); ++acc)
    {
      accounts[acc].addInterest();
     accounts[acc].getId();
     accounts[acc].display();
     for (int inv = 0; inv < investments.size(); ++inv)
      {
     investments[inv].getId();
     investments[inv].display();
     }
    }
   }
  
  cout << endl;  
  ////////////////////////////////////////////////////////
  // Summary of Customer Portfolios
  ////////////////////////////////////////////////////////
  
  //cout << endl;
  //cout << "================================================================================";
  //cout << "*** Summary of Customer Portfolios ***" << endl;
  //cout << "customerID   totalBankBalance   totalInvestValue   grandTotal
" << endl;
  
  
  system("pause");
  return 0;
}  

Answer
Lisa,

you should only display the account if the account's customer ID is the same as the customer you are currently displaying.

The code you sent me is this:
   for(int i = 0; i < customers.size(); ++i) <====================== this is the customer display loop
   {
       customers[i].display();
       for(int acc = 0; acc < accounts.size(); ++acc) <=============== this is the account display loop
       {
         accounts[acc].addInterest();
         accounts[acc].getId();
         accounts[acc].display();
         for (int inv = 0; inv < investments.size(); ++inv) <========== this is the investment display loop
         {
         investments[inv].getId();
         investments[inv].display();
         }
       }
   }

You need to change it so that in the accounts display loop, the accounts[acc].display() is called only if account[acc].getId() is the same as cusotmer[i].getId();

You should do the addInterest step in its own loop BEFORE the customer display loop.

The investment display loop has to be inside the customer display loop, but after the account display loop, NOT inside the account display loop. You don't want to display ALL the investments every time you display ONE of the accounts.

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

©2016 About.com. All rights reserved.