How would I change an array to a vector? - c++

so i have this code which is a checkbook program and i have to use the STL and make it do the same thing so the only thing i can think of to change is the array in it to a vector. If you think i can do more let me know, i'm a beginner level programmer and c++ is one of my weak languages.
template <class DataType>
class Checkbook
{
public:
Checkbook( );
Checkbook( float iBalance );
void setBalance( float amnt );
bool writeCheck( const DataType & amount );
void deposit( float amount );
float getBalance( ) const;
DataType getLastCheck( ) const;
float getLastDeposit( ) const;
private:
float balance;
DataType lastCheck;
float lastDeposit;
};
template <class DataType>
bool operator > (DataType tempcheck, float z)
{
if(tempcheck.amount > z)
return true;
return false;
}
template <class DataType>
float operator - (float z, DataType tempcheck)
{
z = z - tempcheck.amount;
return z;
}
#include<iostream>
using namespace std;
template <class DataType>
Checkbook<DataType>::Checkbook( )
{}
template <class DataType>
Checkbook<DataType>::Checkbook( float initBalance )
{
balance = initBalance;
}
template <class DataType>
void Checkbook<DataType>::setBalance( float amount )
{
balance = amount;
}
template <class DataType>
bool Checkbook<DataType>::writeCheck( const DataType & amount )
{
if ( amount > balance )
return false;
balance = balance - amount;
cout<<"\n\nbalance = "<<balance<<endl<<endl;
lastCheck = amount;
return true;
}
template <class DataType>
void Checkbook<DataType>::deposit( float amount )
{
balance += amount;
lastDeposit = amount;
}
template <class DataType>
float Checkbook<DataType>::getBalance( ) const
{
return balance;
}
template <class DataType>
DataType Checkbook<DataType>::getLastCheck( ) const
{
return lastCheck;
}
template <class DataType>
float Checkbook<DataType>::getLastDeposit( ) const
{
return lastDeposit;
}
#include <iostream>
#include <iomanip>
#include <ctime>
#include <string>
#include <sstream>
using namespace std;
struct Check
{
static string Name;
static string account;
int check;
string checkDate;
float amount;
string comment;
string receipent;
};
string Check::Name = "";
string Check::account = "";
int main( )
{
struct Check ck[100];
float balance;
float Deposit=0.0;
float WriteCheck=0.0;
time_t now = time(0);
tm *ltm = localtime(&now);
string CurrentDate;
stringstream mon, day, year;
int temp;
temp = 1 + ltm->tm_mon;
mon << temp;
temp = ltm->tm_mday;
day << temp;
temp = 1900 + ltm->tm_year;
year << temp;
CurrentDate = mon.str() + "/" + day.str() + "/" + year.str();
cout<<"\nEnter name of Account Holder : ";
getline(cin,Check::Name);
cout<<"\nEnter Account No : ";
getline(cin,Check::account);
cout <<"\nEnter your initial balance: ";
cin >> balance;
Check tempCk;
Checkbook<Check> cbook( balance );
int i=0;
int j;
int choice=0;
do
{
cout<<endl<<"1- Writing checks";
cout<<endl<<"2- Show last checks";
cout<<endl<<"3- Deposit";
cout<<endl<<"4- Show Balance";
cout<<endl<<"5- Quit";
cout<<"\n\nEnter your choice : ";
cin>>choice;
switch(choice)
{
case 1:
cout<<"\nCheck Number : "<<i+1<<endl;
ck[i].check = i+1;
cout<<"\nEnter receipent name : ";
getline(cin,ck[i].receipent);
cout<<"\nEnter amount : ";
cin>>ck[i].amount;
cout<<"\nDate of check : "<<CurrentDate<<endl;
ck[i].checkDate = CurrentDate;
cout<<"\nEnter Comment for check : ";
getline(cin,ck[i].comment);
if(!cbook.writeCheck(ck[i]))
{
cout<<"\n\nNot enough balance "<<ck[i].amount<<endl<<endl;
}
else
i++;
break;
case 2:
cout<<"\n\nDetails of Last Check\n\n";
cout<<"*************************";
for(j = i-1;j>=0;j--)
{
cout<<"\nCheck Number : "<<ck[j].check;
cout<<"\nDate of Check : "<<ck[j].checkDate;
cout<<"\nReceipent : "<<ck[j].receipent;
cout<<"\nAmount on Check : "<<ck[j].amount;
cout<<"\nComment : "<<ck[j].comment;
cout<<"\n*************************\n";
}
break;
case 3:
cout<<"\nEnter amount to deposit : ";
cin>>Deposit;
cbook.deposit(Deposit);
break;
case 4:
cout << fixed << showpoint << setprecision( 3 );
cout << "Current Balance is: " << cbook.getBalance( )<<" " << endl;
break;
default:
if(choice!=5)
cout<<"\n\nInvalid Entry, please try again\n";
}
}while(choice!=5);
return 0;
}
So far all i know is that i need to do this.
Check ck[100]; -> std::vector<Check> ck;

After a quick glance at your code I believe this is the only thing you have to do:
Replace
struct Check ck[100];
with:
std::vector<Check> ck(100);
Or since you have a fixed-size array you could use std::array like this:
std::array<Check,100> ck;

You can declare a local variable, in the main: Check tmp;
And the vector as: std::vector<Check> ck;
when adding new check you work on the local tmp, and when successfully done, add it to the vector.
in your code:
if(!cbook.writeCheck(tmp)){
cout<<"\n\nNot enough balance "<<tmp.amount<<endl<<endl;
}else{
ck.push_back(tmp);
}
Also, you don't need to keep the count or index, since you can use ck.size().

iterate over the ck[] and push_back every item.something like this.
std::vector<Check> ckvector;
for(int i=0;i<100;i++)
ckvector.push_back(ck[i]);

Related

Throwing and Catching exceptions with a template class

What I'm trying to create is a TestScore Template class that just simply calculates the average of a array. I'm trying to throw a exception when a grade is negative or bigger than 100. I have created a NegativeScore exception class and a TooLargeScore exception class,both which just return a string message. In main, i create my array and ask the user for the grades, then use the class to get the average but for some reason it doesnt find the average. It doesnt print out the average when i try to. Im thinking the problem lies with my pointers but i dont know what the exact problem is, anyone know?
#ifndef TESTSCORES_H_INCLUDED
#define TESTSCORES_H_INCLUDED
#include <iostream>
#include "NegativeScore.h"
#include "TooLargeScore.h"
#include <iomanip>
using namespace std;
template <class T>
class TestScores
{
private:
T* testscores[];
public:
TestScores(T testscores[]);
T GetAverage();
};
template <class T>
TestScores<T>::TestScores(T testscores[])
{
*(this->testscores) = testscores;
}
template <class T>
T TestScores<T>::GetAverage()
{
T average;
T sum;
T counter;
for(int i = 0; i <= 5; i++)
{
if(*testscores[i] < 0)
{
throw NegativeScore("Test Score is negative, its invalid!");
}
else if(*testscores[i] > 100)
{
throw TooLargeScore("Test score it too high, its invalid!");
}
else
{
sum = sum + *testscores[i];
}
counter++;
}
average = sum / 5;
return average;
}
MAIN
int main()
{
int MAX = 5;
double scores[MAX];
for(int i = 0; i < MAX; i++)
{
int score;
cout << "Enter the test score for test "<< (i+1) << endl;
cin >> score;
scores[i] = score;
}
try
{
TestScores<double> tests(scores);
tests.GetAverage();
cout << tests.GetAverage() << endl;
}
catch(NegativeScore ex)
{
cout << ex.getMessage() << endl;
}
catch(TooLargeScore ex2)
{
cout << ex2.getMessage() << endl;
}
return 0;
}
Your problem is that you class holds an array of pointer to T, but you attempt to initialize it with a array of double (i.e. array of T values).
template <class T>
class TestScores
{
private:
T* testscores[];
public:
TestScores(T testscores[]);
T GetAverage();
};
template <class T>
TestScores<T>::TestScores(T testscores[])
{
*(this->testscores) = testscores; // <--- This is not doing what you think it is.
}
I am surprised that compiled, and you should strongly consider using a better compiler that will warn you of dubious operations.
You should change the class to hold a plain pointer-to-T, i.e. a T* testscores;, or better, an std::vector<T>.
For example, I could get your code working with this change:
template <class T>
class TestScores
{
private:
T* testscores; // Note simpler pointer to first element of array of length of 5.
public:
TestScores(T testscores[]);
T GetAverage();
};
You also have an error in the limits of your for loop in GetAverage (should not include 5), and your variables in that function are uninitialized and may hold garbage values.

Getting values from a vector of object pointers

I need to write the name, act# balance and address of the object that is stored in the vector, to a file.
I believe I have the program to push the objects into the vectors, but since they are vectors of object pointers I am having problems figure out how to call the object and print all 3 objects out.
Main.cpp
vector<Account*> accounts;
accounts.push_back(new Savings(new Person("Bilbo Baggins", "43 Bag End"), 1, 500, 0.075));
accounts.push_back(new Checking(new Person("Wizard Gandalf", "Crystal Palace"), 2, 1000.00, 2.00));
accounts.push_back(new Savings(new Person("Elf Elrond", "Rivendell"), 3, 1200, 0.050));
ofstream outFile;
outFile.open("accounts.txt");
if (outFile.fail())
{
cout << "\nYour file did not open, the program will now close!\n";
system("PAUSE");
return 0;
}
else
{
cout << "\nBINGO!!! It worked.\n\n";
system("PAUSE");
cout << "\n";
}
// New : Using a loop, send messages to each of the three Account objects to write themselves out to the file.
cout << "\nNow we are going to write the information to \"Accounts.txt\" \n\n";
system("PAUSE");
for (int i = 0; i < accounts.size(); i++) {
accounts[i]->writeAccount(outFile);
}
Account.h
#pragma once
#include <string>
#include <iostream>
#include "Person.h"
using namespace std;
// Account class - abstract/parent class
class Account
{
private:
int actNumber;
double actBallance;
Person PersonName;
public:
Account();
Account(int, double, Person*);
int getActNumber();
virtual double getActBallance();
string getName();
string getAdd();
void deposit(double);
void withdrawl(double);
virtual void writeAccount(ofstream&);
virtual void readAccount(ifstream&);
void testAccount(int i);
};
// Checking class: inherits from the Account class
class Checking : public Account
{
private:
double monthlyFee;
public:
Checking();
Checking(Person*, int, double, double);
void setMonthlyFee(double);
double getActBallance();
void writeAccount(ofstream&);
void readAccount(ifstream&);
};
// Savings class: inherits from the Account class
class Savings : public Account
{
private:
int interestRate;
public:
Savings();
Savings(Person*, int, double, double); // person, act#, Ballance, Interest Rate
void setInterestRate(double);
double getActBallance();
void writeAccount(ofstream&);
void readAccount(ifstream&);
};
Account.cpp
#include "Account.h"
#include <string>
using namespace std;
Account::Account()
{
actNumber = 0;
actBallance = 0.0;
}
Account::Account(int act, double bal, Person* name)
{
actNumber = act;
actBallance = bal;
}
int Account::getActNumber()
{
return actNumber;
}
double Account::getActBallance()
{
return actBallance;
}
string Account::getName()
{
return PersonName.getName();
}
string Account::getAdd()
{
return PersonName.getAddress();
}
void Account::deposit(double money)
{
actBallance += money;
}
void Account::withdrawl(double money)
{
actBallance -= money;
}
void Account::writeAccount(ofstream& output)
{
output << actNumber << "\n" << actBallance << "\n" << PersonName.getName() << "\n" << PersonName.getAddress() << endl;
}
void Account::readAccount(ifstream& output)
{
output >> actNumber;
output >> actBallance;
}
// Checking Account
Checking::Checking() {
monthlyFee = 0;
}
Checking::Checking(Person* per, int actNum, double bal, double interest) {
bal -= monthlyFee;
Account:Account(actNum, bal, per);
}
void Checking::setMonthlyFee(double fee) {
monthlyFee = fee;
}
double Checking::getActBallance() {
double ballance = Account::getActBallance();
return ballance = monthlyFee;
}
void Checking::readAccount(ifstream& output) {
int actNumber = Account::getActNumber();
int actBallance = Account::getActBallance() - monthlyFee;
output >> actNumber;
output >> actBallance;
}
void Checking::writeAccount(ofstream& output) {
int actNumber = Account::getActNumber();
int actBallance = Account::getActBallance();
output << actNumber << "\n" << actBallance << endl;
}
// Savings Account
Savings::Savings() {
interestRate = 0;
}
// Savings(Person, int, double, double) // person, act#, Ballance, Interest Rate
Savings::Savings(Person* per, int actNum, double bal, double interest) {
bal += (bal * interest);
Account:Account(actNum, bal, per);
}
void Savings::setInterestRate(double rate) {
interestRate = rate;
}
double Savings::getActBallance() {
double ballance = Account::getActBallance();
return ballance + (ballance * interestRate);
}
void Savings::readAccount(ifstream& output) {
double actBallance = Account::getActBallance();
int actNumber = Account::getActNumber();
actBallance += (actBallance * interestRate);
output >> actNumber;
output >> actBallance;
}
void Savings::writeAccount(ofstream& output) {
int actNumber = Account::getActNumber();
int actBallance = Account::getActBallance();
output << actNumber << "\n" << actBallance << endl;
}
I realize I am so far off... but I have been at this for HOURS and I can not figure out for the life of me, but to take the vector of object pointers and output the objects values.
Person.h
#pragma once
#include <string>
#include <fstream>
using namespace std;
class Person
{
private:
string name;
string address;
public:
Person();
Person(string a, string b);
string getName();
string getAddress();
void writePerson(ofstream&);
void readPerson(ifstream&);
};
Person.cpp
#include "Person.h"
#include <string>
using namespace std;
Person::Person()
{
name = "NAME";
address = "123 STREET";
}
Person::Person(string a, string b)
{
name = a;
address = b;
}
string Person::getName()
{
return name;
}
string Person::getAddress()
{
return address;
}
void Person::writePerson(ofstream& output)
{
output << name << " " << address << endl;
}
void Person::readPerson(ifstream& output)
{
output >> name;
output >> address;
Person(name, address);
}
Read again your course books on constructors: there are severe issues in all of your constructors. As a result, you don't initialize the object member variables, and you effectively end up printing lots of zeros and empty strings...
Firstly, for your base-class, you must initialize the person name. You should have written:
Account::Account(int act, double bal, Person* name)
: actNumber(act)
, actBallance(bal)
, PersonName(name)
{}
Secondly, for your derived classes, the initialisation of the base-class must be done in the initializer-list, not in the body of the ctor. Here is for exemple the correct definition for the Checking's ctor:
Checking::Checking(Person* per, int actNum, double bal, double interest)
: Account(actNum, bal, per)
, monthlyFee(-bal)
{}
Thirdly, be careful to initialize the member variables with the arguments of the ctor. You sometimes do the opposite and assign the ctor arguments with the (uninitialized) member variables.
BTW, Account is a base-class for a polymorphic hierarchy: thus, the Account destructor must be declared virtual.

C++ Read inFile separated by a comma and a space

i am required to read a file with data of this format (Date, ID, Activity, Qty, Price) in the main test class. I'm supposed to read and store the "Date" values into int day,month,year of type Date, followed by "ID, Activity, Qty, Price" of stock class.
02/08/2011, ABC, BUY, 100, 20.00
05/08/2011, ABC, BUY, 20, 24.00
06/08/2011, ABC, BUY, 200, 36.00
i stored the values accordingly to Stock() constructor and store all data via push_back() in my own "Vector" class. what must i add/ edit so that i can retrieve the rows of data in Vector and get(Date, ID, Activity, Qty, Price) and make calculations for qty and price.
#include"Vector.h"
#include"Date.h"
#include"Stock.h"
#include<iomanip>
#include<fstream>
#include<iostream>
#include<string>
using namespace std;
int main(){
string stockcode;
string act;
int qty;
double p;
int d,m,y;
char x;
//declare file stream variables
ifstream inFile;
ofstream outFile;
//open the file
inFile.open("share-data.txt");
//code for data manipulation
cout << fixed << showpoint << setprecision(2);
while(!inFile.eof()){
inFile>> d >> x >> m >> x >> y >> x
>> stockcode >> act >> qty >> x >> p;
Stock s1(d,m,y,stockcode,act,qty,p);
stockcode = stockcode.substr(0, stockcode.length()-1);
act = act.substr(0, act.length()-1);
Stock s1(d,m,y,stockcode,act,qty,p);
stockList.push_back(s1);
}
inFile.close();
system("PAUSE");
return 0;
}
i have my own Vector class which is needed for this assignment because i am not allowed to use #include default vector
#include<iostream>
using namespace std;
template <class T>
class Vector
{
public:
Vector(); // default constructor
virtual ~Vector() {}; //destructor
bool isEmpty() const;
bool isFull() const;
void print() const;
void push_back(T);
T pop_back();
T at(int i);
int Size();
//Vector<T> operator +=(T);
private:
int size;
T list[100];
};
template <class T>
Vector<T>::Vector()
{
size = 0;
}
template <class T>
Vector<T> Vector<T>::operator +=(T i)
{
this->push_back(i);
return *this;
}
template <class T>
bool Vector<T>::isEmpty() const
{
return (size == 0);
}
template <class T>
bool Vector<T>::isFull() const
{
return (size == 100);
}
template <class T>
void Vector<T>::push_back(T x)
{
list[size] = x;
size++;
}
template <class T>
T Vector<T>::operator[](T i)
{
return list[i];
}
template <class T>
T Vector<T>::at(int i)
{
if(i<size)
return list[i];
throw 10;
}
template <class T>
T Vector<T>::pop_back()
{
T y;
size--;
y= list[size];
return y;
}
template <class T>
void Vector<T>::print() const
{
for (int i = 0; i < size; i++)
cout << list[i] << " ";
cout << endl;
}
template <class T>
int Vector<T>::Size()
{
return size;
}
and here's my Stock class
#include"Date.h"
Stock::Stock()
{
stockID="";
act="";
qty=0;
price=0.0;
}
Stock::Stock(int d, int m , int y, string id,string a, int q, double p)
:date(d,m,y){
stockID = id;
act = a;
qty = q;
price = p;
}
.
.
.
use string::substr
act = act.substr(0, act.length()-1);
You can do the same for the other string variables.

C++: Class Issues

I'm attempting to make my class do the following...
EmployeeHandler: Initializes m_employeeCount to zero.
AddEmployee: Invoked by menu option 1. Displays "NEW EMPLOYEE". Prompts the user for
the employee’s first name, last name, and pay rate, one at a time. Uses Employee.Setup to add
an employee to m_lstEmployee. Displays "Employee m_employeeCount added". Increments
m_employeeCount.
EmployeeSelection: Displays the list of employees, by index; prompts the user for an employee
index and returns the index.
EditEmployee: Invoked by menu option 2. Uses EmployeeSelection to get the index of the
employee to edit. Verifies if the index is valid and displays an error message if it is not. Uses
Employee.Output to display the selected employee’s current information. Prompts the user for
the employee’s new first name, last name, and pay rate, one at a time. Uses Employee.Setup to
change the employee’s information in m_lstEmployee. Displays “** Employee index updated”,
where index is the user selected index.
LayoffEmployee: Invoked by menu option 3. Uses EmployeeSelection to get the index of the
employee to lay-off. Uses Employee.Output to display the selected employee’s first name, last
name, and pay rate. Uses Employee.LayOff to lay the employee off. Displays "Employee
index laid off", where index is laid off employee’s index.
DisplayEmployeeList: Invoked by menu option 4. Displays "EMPLOYEES". Then uses
Employee.Output to display every employee record something like this, "[1] David Johnson,
PAY: $5.00 (CURRENT EMPLOYEE)" and a former employee record something like this, "[2]
David Johnson, PAY: $5.00 (FORMER EMPLOYEE)", where the number in the brackets is the
employee’s index in m_lstEmployee.
GetEmployee: Returns the address of the selected employee record in m_lstEmployee.
GetEmployeeCount: Returns the number of employees in m_employeeCount.
So far I have...
#ifndef _EMPLOYEEHANDLER
#define _EMPLOYEEHANDLER
#include "Employee.h"
class EmployeeHandler
{
public:
EmployeeHandler()
{
m_employeeCount = 0; //undefined?
};
void AddEmployee()
{
string firstName;
string lastName;
float payRate;
cout<<"NEW EMPLOYEE"<<endl;
cout<<"First Name:"<<endl;
cin>>firstName;
cout<<"Last Name:"<<endl;
cin>>lastName;
cout<<"Pay Rate:"<<endl;
cin>>payRate;
Employee.Setup(firstName,lastName,payRate); //Problem here
cout<<"**Employee m_employeeCount added"<<endl;
m_employeeCount+=1; //m_employeeCount undefined?
}
void EditEmployee()
{
int indexEdit;
string newFirst;
string newLast;
float newPay;
cout<<"Which employee would you like to edit"<<endl;
cin>>indexEdit;
EmployeeSelection(indexEdit); //undefined?
Employee.Output(); //
cout<<"Employee new first name:"<<endl;
cin>>newFirst;
cout<<"Employee new last name:"<<endl;
cin>>newLast;
cout<<"Employee new pay rate:"<<endl;
cin>>newPay;
Employee.Setup(newFirst,newLast,newPay); ///
cout<<"** Employee index updated"<<endl;
}
void LayoffEmployee()
{
EmployeeSelection();
Employee.Output(EmployeeSelection); //Problems here
Employee.LayOff(EmployeeSelection);
cout<<"Employee laid off"<<endl;
}
void DisplayEmployeeList()
{
cout<<"EMPLOYEES"<<endl;
for (int i=0; i<50; i++)
cout<<[i]<<Employee.Output(m_1stEmployee)<<endl; //
}
int EmployeeSelection()
{
int indexNumber;
for (int i= 0; i <50; i++)
cout<<[i]m_1stEmployee<<endl; //
cout<<"Which Employee Index would you like to select?"<<endl;
cin>>indexNumber;
for (int i = 0; i <50; i++)
if ([i]=indexNumber) //
return [i]
}
Employee& GetEmployee( int index )
{if (index=; // completely confused here
}
int GetEmployeeCount()
{
return m_employeeCount;
};
private:
Employee m_lstEmployee[50];
int m_employeeCount;
};
#endif
The employee.h file is as follows...
#ifndef _EMPLOYEE
#define _EMPLOYEE
#include<iostream>
#include<iomanip>
#include <string>
using namespace std;
class Employee
{
public:
void Setup( const string& first, const string& last, float pay );
{
m_firstName = first;
m_lastName = last;
m_payPerHour = pay;
m_activeEmployee = true;
}
string GetName()
{
return m_firstName+""+m_lastName
};
bool GetIsActive()
{
return m_activeEmployee;
};
void LayOff()
{
m_activeEmployee= false;
};
void Output()
cout<<GetName()<<",PAY:$"<<fixed<<setprecision(2)<<m_payPerHour<<endl;
private:
string m_firstName;
string m_lastName;
float m_payPerHour;
bool m_activeEmployee;
};
#endif
I've been stuck writing this class for the last two days trying to figure out what I'm doing wrong. This is the first time I've attempted to write classes in C++. Any and all help is much, much appreciated. I have marked places where I'm having problems with //.
Your code has many, many problems...
I'll start by providing compilable code that more or less does what you want. I'm not sure how you can go about asking questions, but compare it to your own code and read a good c++ book...
I've replaced your array with a vector. I've used a constructor to initialize Employee. I've (to my own dismay) added std, mainly because Employee shall live in its own header and it's not good to use a namespace in a header.
In c++ the operator[] is postfix (after the indexed expression).
Also, under normal circumstances I'll try and keep interface and implementation seperate where possible. At the least I would not use inline functions if not absolutely necessary.
The new code...:
#include <iostream>
#include <iomanip>
#include <vector>
#include <iterator>
#include <string>
class Employee
{
public:
//This is a constructor....
Employee( const std::string& first, const std::string& last, float pay )
//The members can be initialized in a constructor initializer list as below.
: m_firstName( first ), m_lastName( last ), m_payPerHour( pay ),
m_activeEmployee() //Scalars are initialized to zero - bool to false...
{
}
std::string GetName() const
{
return m_firstName+" "+m_lastName;
}
bool GetIsActive() const
{
return m_activeEmployee;
};
void LayOff()
{
m_activeEmployee = false;
}
std::ostream& Output( std::ostream& out ) const
{
return out << GetName() <<",PAY:$"
<< std::fixed << std::setprecision(2) << m_payPerHour;
}
private:
std::string m_firstName;
std::string m_lastName;
float m_payPerHour;
bool m_activeEmployee;
};
inline std::ostream& operator << ( std::ostream& os, const Employee& employee )
{
return( employee.Output( os ) );
}
class EmployeeHandler
{
public:
void AddEmployee()
{
std::string firstName;
std::string lastName;
float payRate;
std::cout<<"NEW EMPLOYEE"<<std::endl;
std::cout<<"First Name:"<<std::endl;
std::cin>>firstName;
std::cout<<"Last Name:"<<std::endl;
std::cin>>lastName;
std::cout<<"Pay Rate:"<<std::endl;
std::cin>>payRate;
employees_.push_back( Employee( firstName,lastName,payRate ) );
std::cout<<"**Employee m_employeeCount added"<<std::endl;
}
void EditEmployee()
{
std::string newFirst;
std::string newLast;
float newPay;
std::cout<<"Which employee would you like to edit"<<std::endl;
int indexEdit = GetSelection();
Employee& employee = employees_[indexEdit];
std::cout << employee << std::endl;
std::cout<<"Employee new first name:"<<std::endl;
std::cin>>newFirst;
std::cout<<"Employee new last name:"<<std::endl;
std::cin>>newLast;
std::cout<<"Employee new pay rate:"<<std::endl;
std::cin>>newPay;
employee = Employee( newFirst, newLast, newPay );
std::cout<<"** Employee index updated"<<std::endl;
}
void LayoffEmployee()
{
int index = GetSelection();
if( employees_[index].GetIsActive() )
{
std::cout << "Laying off employee:\n" << employees_[index] << std::endl;
employees_[index].LayOff();
}
else
{
std::cerr << "Already layed off employee:" << employees_[index] << std::endl;
}
}
void DisplayEmployeeList()
{
std::copy( employees_.begin(), employees_.end(), std::ostream_iterator<Employee>( std::cout, "\n" ) );
}
int GetSelection()
{
std::size_t indexNumber;
std::cout << "Select an employee from the list below by specifying its number:" << std::endl;
DisplayEmployeeList();
do{
while( !std::cin >> indexNumber )
{
std::cin.clear();
std::cin.ignore();
std::cerr << "Select a number..." << std::endl;
}
if( indexNumber >= employees_.size() )
{
std::cerr << "Select a number within range of list below:" << std::endl;
DisplayEmployeeList();
}
}
while( indexNumber >= employees_.size() );
return indexNumber;
}
Employee& operator[]( std::size_t index )
{
return employees_[index];
}
const Employee& operator[]( std::size_t index ) const
{
return employees_[index];
}
std::size_t EmployeeCount() const
{
return employees_.size();
}
private:
std::vector<Employee> employees_;
};
int main( int argc, char* argv[] )
{
return 0;
}
Finally - the code is merely compiled, not tested. I suspect I might have made a mistake, but alas, time!!!

Unable to remove missing ; before variable name error

#ifndef PRODUCTS_H
#define PRODUCTS_H
#include "Products.h"
class Products
{
protected:
static int count;
string name_;
float cost_;
public:
Products() // default ctor
{
name_ = "";
cost_ = 0.0f;
count++;
}
Products(string name , float cost) //parametorized ctor
{
name_ = name;
cost_ = cost;
count++;
}
Products(Products &p )
{
name_ = p -> name_;
cost_ = p -> cost_;
}
~Products()
{}
string getName()
{
return name_;
}
void setName(string name)
{
name_=name;
}
float getCost()
{
return cost_;
}
void setCost(float cost)
{
cost_=cost
}
float CalcTotal(Products *p_products) //Not made yet!
{
float total=0.0f;
for(int i = 0 ; i < count; i++)
{
total += p_products->cost_;
p_products ++;
}
return total;
}
Products read()
{
Products size,*p_products;
cout << "Enter Number of Items To Enter:";
cin >> size;
cout << endl;
p_products = new Products[size];
for(int i = 0 ; i < size; i++)
{
cout << "Enter Name:";
cin >> p_products -> name_;
cout << endl << "Enter Cost";
cin >> p_products -> cost_;
cout << endl;
p_products ++;
}
return p_products;
}
void write(Products *p_products)
{
for(int i = 0 ; i < count ; i++,p_products++)
{
cout<<"Products Name:\t\t"<<p_products->name_<<endl;
cout<<"Products Price:\t\t"<<p_products->cost_<<endl;
}
}
};
#endif
My source code is:
#include <iostream>
#include <string>
#include "Products.h"
using namespace std;
static int Products::count;//declaring static variable
int main()
{
Products *p_products,temp;
*p_products=temp.read();
//temp.write();
system("pause");
delete[] Product;
return 0;
}
But I am getting this error which I can not remove:
error C2146: syntax error : missing
';' before identifier 'name_'
Please help me out!Thanks
You should include the string header file in your first file. It looks like it's complaining that it doesn't know what a string is.
You need to add
#include <string>
and change the type of name_ to
std::string name_;
In Products &p, p is a reference to an object of type Products, it's not a pointer.
You have to use operator ., instead of operator -> in order to access reference fields:
Products(Products &p )
{
name_ = p -> name_;
cost_ = p -> cost_;
}
Try moving this line:
using namespace std;
Above the line where you #include "Products.h". But if you're using string in products.h, you should probably be including etc there instead. Also, I believe "using namespace std" is kinda frowned upon.
in your include file, you must declare the string name_ as std::string name_
You need:
std::string name_;
Also, looks like a missing semicolon here:
void setCost(float cost)
{
cost_=cost
}
You're missing a semicolon in this function:
void setCost(float cost)
{
cost_=cost
}