I am looking for an easy way to save and load this C++ object to and from a binary file.
#include <iostream>
#include <vector>
class User
{
private:
std::string _name;
int _age;
std::vector<std::string> _hobbies;
public:
std::string Name() { return _name; }
int Age() { return _age; }
std::vector<std::string> Hobbies() { return _hobbies; }
void Hobbies(std::string hobbieName)
{
_hobbies.push_back(hobbieName);
}
User(std::string name, int age)
{
_name = name;
_age = age;
}
};
int main()
{
User u1 = User("John", 48);
u1.Hobbies("Art");
u1.Hobbies("Lego");
u1.Hobbies("Blogging");
User u2 = User("Jane", 37);
u2.Hobbies("Walking");
u2.Hobbies("Chess");
u2.Hobbies("Card Games");
std::cout << u1.Name() << "'s Hobbies:\n";
for (std::string hobbie : u1.Hobbies())
{
std::cout << hobbie << "\n";
}
std::cout << u2.Name() << "'s Hobbies:\n";
for (std::string hobbie : u2.Hobbies())
{
std::cout << hobbie << "\n";
}
//Save 'u1' to file.
//Load 'u1' from file into a new 'User' object
}
I have looked at a number of StackOverflow answers for similar questions, but I am struggling to find a solution specifically regarding using the vector in my class. I would appreciate any suggestions that you might have.
Here is a very abstract idea of what you want, Write string size that helps to read string back for name, write age, again wite hobbies size that helps to read it again and finally write each string with it size. To read reverse the process,
#include <iostream>
#include <fstream>
#include <vector>
class User
{
private:
std::string _name;
int _age;
std::vector<std::string> _hobbies;
public:
std::string Name()
{
return _name;
}
int Age()
{
return _age;
}
std::vector<std::string> Hobbies()
{
return _hobbies;
}
void Hobbies(std::string hobbieName)
{
_hobbies.push_back(hobbieName);
}
User(std::string name, int age)
{
_name = name;
_age = age;
}
/**
* #brief saves to user binary file
*
* #param fout
*/
void save(std::ofstream &fout)
{
// write name
size_t nsiz = this->_name.size();
// write string size to read
fout.write((const char *)(&nsiz), sizeof(nsiz));
fout.write(&_name[0], nsiz);
// write age
fout.write((const char *)&_age, sizeof(int));
// write hobbies size
size_t hsiz = _hobbies.size();
fout.write((const char *)&hsiz, sizeof(size_t));
// write hobbies
for (auto &str : _hobbies)
{
size_t ssiz = str.size();
fout.write((const char *)(&ssiz), sizeof(ssiz));
fout.write(&str[0], str.size());
}
}
/**
* #brief loads from binary file
*
* #param fin
*/
void load(std::ifstream &fin)
{
// read name
size_t nsiz = 0;
fin.read((char*)&nsiz, sizeof(size_t));
this->_name.resize(nsiz);
fin.read(&_name[0], nsiz);
// read age
fin.read((char*)&_age, sizeof(int));
// read hobbies size
size_t hsiz = 0;
fin.read((char*)(&hsiz), sizeof(hsiz));
_hobbies.resize(hsiz);
for(size_t i = 0; i < hsiz; ++i)
{
size_t ssiz = 0;
fin.read((char*)&ssiz, sizeof(size_t));
_hobbies[i].resize(ssiz);
fin.read(&_hobbies[i][0], ssiz);
}
}
};
int main()
{
User u1 = User("John", 48);
u1.Hobbies("Art");
u1.Hobbies("Lego");
u1.Hobbies("Blogging");
std::ofstream fout("data.bin", std::ofstream::binary);
u1.save(fout);
fout.close();
User u2("", 0);
std::ifstream fin("data.bin", std::ifstream::binary);
u2.load(fin);
fin.close();
std::cout << u2.Name() << " with age " << u2.Age() << "'s Hobbies:\n";
for (std::string hobbie : u2.Hobbies())
{
std::cout << hobbie << "\n";
}
}
I hope that it helps, and make sure to do things what if string size is zero :)
Related
If we have a vector of struct pointer MyInfo* (allocated on heap). Then we can check vec[i] == NULL to know whether there is a struct in the vec[i], like this, if (vec[i] != NULL) //then do some processing
However, if we allocate MyInfo on stack instead of on heap, then we have vector<MyInfo> as shown below. I guess each vec[i] is initialized by the struct default constructor. How do you check whether vec[i] contains a non-empty struct similar to above NULL pointer case, like if (vec[i] contains valid struct) //then do some processing
My code is below
#include <iostream> // std::cout
#include <string>
#include <vector>
using namespace std;
struct MyInfo {
string name;
int age;
};
int main () {
vector<MyInfo> vec(5);
cout << "vec.size(): " << vec.size() << endl;
auto x = vec[0];
cout << x.name << endl; //this print "" empty string
cout << x.age << endl; //this print 0
return 0;
}
There are some options you can use. The first and easiest one, is to define a value to each (or for one) of your struct's variables, that will point that the struct is not initialized yet. In this case, age should be large or equal to 0, to be logicly straight. So, you can initialize it to -1, like this:
struct MyInfo {
string name;
int age = -1;
};
// Or
struct MyInfo {
string name;
int age;
MyInfo() : name(""), age(-1) {} // Use constructor
};
Now, in your main function, it will print in the age the value -1. Also, you can see the empty of the name variable as a sign for it too.
Another way might be using flag and get/set operations to indicate when the variables are initialize:
struct MyInfo {
private:
std::string _name;
int _age;
bool age_initialize = false;
bool name_initialize = false;
public:
void name(const std::string &name_p) { _name = name_p; name_initialize = true; }
void age(int age_p) { _age = age_p; age_initialize = true; }
void init(int age_p, const std::string &name_p) { age(age_p); name(name_p); }
bool is_initialize() { return name_initialize && age_initialize; }
int age() { return _age; }
std::string name() { return _name; }
};
int main() {
std::vector<MyInfo> vec(5);
std::cout << "vec.size(): " << vec.size() << std::endl;
auto x = vec[0];
std::cout << x.is_initialize() << std::endl; //this print 0
std::cout << x.name() << std::endl; //this print "" empty string
std::cout << x.age() << std::endl; //this print 0
return 0;
}
You can also throw an exception when calling int age() of std::string name() function, if those values are not initialize yet:
struct MyInfo {
private:
/* ... */
public:
/* ... */
int age() {
if (!age_initialize) throw std::runtime_error("Please initialize age first.");
return _age;
}
std::string name() {
if (!name_initialize) throw std::runtime_error("Please initialize name first.");
return _name;
}
};
Hi I'm quite new to c++ and I have a project but to do but a question in the project requires me to add a function, getAverageCostPerDay(), which takes a vector of Reservations object and returns the average cost of a car reservation. How do I got about doing this? Thanks
Reservation.h
#pragma once
#include <string>
class Reservation
{
private:
int id;
std::string name;
int stDate;
int stMonth;
int stYear;
int duration;
float cost;
std::string licensePlate;
static int reservationCount;
public:
//Constructor
Reservation();
Reservation(int id, std::string name, int stDate, int stMonth, int
stYear, int duration, float cost, std::string licensePlate);
//Destructor
~Reservation();
//Getters
int getId();
std::string getName();
int getStDate();
int getStMonth();
int getStYear();
int getDuration();
float getCost();
std::string getLicensePlate();
//Setters
void setId(int id);
void setName(std::string name);
void setStDate(int stDate);
void setStMonth(int stMonth);
void setStYear(int stYear);
void setDuration(int duration);
void setCost(float cost);
void setLicensePlate(std::string licensePlate);
static int getReservationCount()
{
return reservationCount;
}
};
Reservation.cpp
#include "pch.h"
#include "Reservation.h"
int Reservation::reservationCount = 0;
//Constructor
Reservation::Reservation()
{
this->id = 0;
this->name = "";
this->stDate = 0;
this->stMonth = 0;
this->stYear = 0;
this->duration = 0;
this->cost = 0;
this->licensePlate = "";
reservationCount++;
}
Reservation::Reservation(int id, std::string name, int stDate, int stMonth,
int stYear, int duration, float cost, std::string licensePlate)
{
this->id = id;
this->name = name;
this->stDate = stDate;
this->stMonth = stMonth;
this->stYear = stYear;
this->duration = duration;
this->cost = cost;
this->licensePlate = licensePlate;
reservationCount++;
}
//Destructor
Reservation::~Reservation()
{
reservationCount--;
std::cout << "Destroying (" << this->name << ")" << std::endl;
}
//Getters
int Reservation::getId()
{
return this->id;
}
std::string Reservation::getName()
{
return this->name;
}
int Reservation::getStDate()
{
return this->stDate;
}
int Reservation::getStMonth()
{
return this->stMonth;
}
int Reservation::getStYear()
{
return this->stYear;
}
int Reservation::getDuration()
{
return this->duration;
}
float Reservation::getCost()
{
return this->cost;
}
std::string Reservation::getLicensePlate()
{
return this->licensePlate;
}
//Setters
void Reservation::setId(int id)
{
this->id = id;
}
void Reservation::setName(std::string name)
{
this->name = name;
}
void Reservation::setStDate(int stDate)
{
this->stDate = stDate;
}
void Reservation::setStMonth(int stMonth)
{
this->stMonth = stMonth;
}
void Reservation::setStYear(int stYear)
{
this->stYear = stYear;
}
void Reservation::setDuration(int duration)
{
this->duration = duration;
}
void Reservation::setCost(float cost)
{
this->cost = cost;
}
void Reservation::setLicensePlate(std::string licensePlate)
{
this->licensePlate = licensePlate;
}
Main.cpp
#include "pch.h"
#include "Reservation.h"
//Regular Expressions
std::string idRegexStr = "[0-9]{3,4}";
std::string nameRegexStr = "[A-Za-z]{1}[a-z]{1,30} [A-Za-z]{1}[a-z]{1,30}";
std::string stDateRegexStr = "[0-3]{1}[0-9]{1}";
std::string stMonthRegexStr = "[0-1]{1}[0-9]{1}";
std::string stYearRegexStr = "[1-2]{1}[0-9]{1}[0-9]{1}[0-9]{1}";
std::string durationRegexStr = "[1-9]{1}[0-9]{1}";
std::string costRegexStr = "[0-9]{2}.[0-9]{2}";
std::string licencePlateRegexStr = "[0-9]{2,3}\\s*[A-Z]{2,3}\\s*[0-9]+";
//Validates data against a user-defined string
bool validate(std::string regexStr, std::string data)
{
return std::regex_match(data, std::regex(regexStr));
}
std::vector<Reservation>populateVector(Reservation defaultVector, int size)
{
std::vector<Reservation> outVector;
for (int i = 0; i < size; i++)
{
outVector.push_back(defaultVector);
}
return outVector;
}
double getAverageCostPerDay(const std::vector<Reservation> outVector)
{
double average = 0;
for (std::size_t i = 0; i < outVector.size(); i++)
{
average = std::vector<Reservation>outVector.at(float cost);
}
return true;
}
int main()
{
/*
//these were example values to see if regex works
bool idIsValid = validate(idRegexStr, "101");
bool nameIsValid = validate(nameRegexStr, "John Smith");
bool stDateIsValid = validate(stDateRegexStr, "24");
bool stMonthIsValid = validate(stMonthRegexStr, "10");
bool stYearIsValid = validate(stYearRegexStr, "2018");
bool durationIsValid = validate(durationRegexStr, "10");
bool costIsValid = validate(costRegexStr, "22.50");
bool licenseIsValid = validate(licencePlateRegexStr, "181 LH 555");
std::cout << "Invalid = 0 / Valid = 1\n";
std::cout << "\n";
std::cout << "Valid ID: " << idIsValid << std::endl;
std::cout << "Valid Name: " << nameIsValid << std::endl;
std::cout << "Valid Start Date: " << stDateIsValid << std::endl;
std::cout << "Valid Start Month: " << stMonthIsValid << std::endl;
std::cout << "Valid Start Year: " << stYearIsValid << std::endl;
std::cout << "Valid Duration: " << durationIsValid << std::endl;
std::cout << "Valid Cost: " << costIsValid << std::endl;
std::cout << "Valid License: " << licenseIsValid << std::endl;
*/
Reservation r1(101, "John Smith", 24, 10, 2018, 4, 22.50, "181 LH
5555");
Reservation r2(102, "Jane Caroll", 31, 01, 2017, 6, 34.25, "161 DUB
55454");
Reservation r3(103, "Sean Morrissey", 16, 06, 2014, 2, 67.50, "162 WEX
83675");
Reservation r4(104, "Billy Joe", 04, 03, 2016, 8, 51.20, "152 DUB
10347");
std::cout << "Reservation Count: " << Reservation::getReservationCount()
<<
std::endl;
}
There are a couple of ways to do this.
You could wrap your vector of reservations inside of a class and keep track of how many there are, what the total cost is, and calculate the average.
However, if you have to return this information through the Reservation class, then you'll have to use a static variable for sum of costs and number of reservation objects. Static attributes are available in all objects of that class and will have the same value between all objects. So, every time you create a Reservation object, increment the count and sum of costs. Then when you need the average, you can calculate it from any of the objects or through the class (if you make a static function to do this).
I am new programming and C++. I am trying to create a Roster of Person objects using an array and then printing the attributes of the People in the Roster.
When I attempt to add a Person to the personArray, I am getting an
Exception = EXC_BAD_ACCESS (code=1, address=0x0).
I think this has to do with the scope of my personArray but I can't seem to figure it out.
Here is the code I am using:
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
class Person
{
public:
Person(string name, int age);
string getName() {
return name;
}
void setName(string n) {
name = n;
}
int getAge() {
return age;
}
void setAge(int a) {
age = a;
}
private:
string name;
int age;
};
class Roster {
public:
void addToPersonArray(string name, string age) {
Person person(name, stoi(age));
personArray[personCount] = &person;
}
void printPersonArray() {
for (int i = 0; i < 5; i++)
cout << personArray[i]->getName() << '\t' << personArray[i]->getAge() << '\n';
}
private:
Person *personArray[5];
int personCount = 0;
};
int main() {
const string studentData[] = {"Dan,45", "Mark,33", "Mary,22",
"April,17", "Jill,22"};
Roster roster;
stringstream ss(studentData[0]); // just testing the first entry
vector<string> result;
while (ss.good()) {
string substr;
getline(ss, substr, ',');
result.push_back(substr);
}
roster.printPersonArray();
}
The problem is here:
void addToPersonArray(string name, string age) {
Person person(name, stoi(age));
personArray[personCount] = &person;
}
person is a local variable in the member function addToPersonArray(), which will be destroyed after the function scope.
Hence, storing the address of a local variable(and trying to accessing it latter in printPersonArray()) will give you, nothing but an undefined behavior.
You are lucky that your programme got the exception.
One more thing to note that, you are not actually using your roster to test the program. Instead, all you do is parsing and saving to result vector. You can add this after the while loop, to make it actually work.
if (result.size() == 2) {
roster.addToPersonArray(result[0], result[1]);
}
Suggestion: Since you have a fixed array size, you probably wanna do it with std::array<Person, 5> or with std::vector<Person> by reserving the memory for 5 Person in the c'tor of Roster.
See a sample output: https://wandbox.org/permlink/tAGqqnhCfwz1wPrH
#include <iostream>
#include <sstream>
#include <vector>
#include <array>
class Person {
public:
Person(const std::string& name, int age): name(name), age(age) {}
std::string getName()const { return name; }
void setName(const std::string& n){ name = n; }
int getAge()const { return age; }
void setAge(int a) { age = a; }
private:
std::string name;
int age;
};
class Roster {
public:
Roster() { personArray.reserve(5); } // reserve some memory
void addToPersonArray(const std::string& name, const std::string& age) {
personArray.emplace_back(name, stoi(age));
}
void printPersonArray() {
// use range loop, which will assure, access what you have.
for (const Person& person: personArray)
std::cout << person.getName() << '\t' << person.getAge() << '\n';
}
private:
std::vector<Person> personArray;
//int personCount = 0; --------------> no need anymore
};
int main() {
std::array<std::string,5> studentData{ "Dan,45", "Mark,33", "Mary,22", "April,17", "Jill,22" };
Roster roster;
for(const std::string& str: studentData)
{
std::stringstream ss(str);
std::vector<std::string> result;
while (ss.good()) {
std::string substr;
std::getline(ss, substr, ',');
result.emplace_back(substr);
}
if (result.size() == 2) {
roster.addToPersonArray(result
[0], result[1]);
}
}
roster.printPersonArray();
return 0;
}
Output:
Dan 45
Mark 33
Mary 22
April 17
Jill 22
In addition to storing pointers to local variables in your addToPersonArray() function, your main() function does not add any entries to the personArray.
Instead, main creates a Roster object, and after some code that doesn't affect anything with Roster, you go straight into calling roster.printPersonArray, which does this:
void printPersonArray()
{
for (int i = 0; i < 5; i++) // <-- This will loop for all 5 entries
cout << personArray[i]->getName() << '\t' << personArray[i]->getAge() << '\n';
}
Since personArray was never initialized to contain valid pointers to Person objects, that loop will cause undefined behavior.
The issue is that you have a personCount member variable, but fail to make use of it to control how many valid entries there are in the array. The loop should have been written as below:
void printPersonArray()
{
for (int i = 0; i < personCount; i++)
cout << personArray[i]->getName() << '\t' << personArray[i]->getAge() << '\n';
}
In addition to the storage of pointers to local variables, your Roster::addToPersonArray() doesn't check if personCount is greater than 4, thus this is another place in your code where you failed to use personCount to control how many Person objects are being referenced.
For a project I'm doing we have to populate a queue with "House" objects. The "House" objects get their information from a file called "data.dat". Each line of the file is another thing that goes into the house object. So first I take a char* for the address, then an int, another int, a third int, and then another char*. We aren't aloud to use strings to get the char* variables which I believe is where I'm running into my problem. Every time I compile it tells me I have a segmentation fault. Here is the area of my queue.cpp that I'm pretty sure the error is in
#include"queue.h"
#include<iostream>
#include<fstream>
#include<istream>
Queue::Queue(const char *filename){
head = NULL;
tail = NULL;
std::ifstream infile(filename);
char * address = NULL;
int footage = 0;
int bedrooms = 0;
int bathrooms = 0;
char * features = NULL;
while(!infile.eof()){
while(infile.get() != '\n'){
//std::cout << infile.get();
infile.get(address[i]);
}
infile >> footage >> bedrooms >> bathrooms;
while(infile.get() != '\n'){
infile.get(features[i]);
}
enqueue(House(address, footage, bedrooms, bathrooms, features));
}
infile.close();
}
Here is the house object header file:
House();
House(char * ad, int fo, int be, int ba, char * fe);
char * getAddress();
int getFootage();
int getBedrooms();
int getBathrooms();
char * getFeatures();
void setAddress(char * ad);
void setFootage(int fo);
void setBedrooms(int be);
void setBathrooms(int ba);
void setFeatures(char * fe);
friend std::ostream& operator<<(std::ostream& out, House& house);
private:
char * address;
int footage;
int bedrooms;
int bathrooms;
char * features;
};
You need to initialize the features and address first, either by using new or by creating it as array of chars of some length.
The way you do it you're trying to write to the memory that was't assigned yet - hence buffer overflow.
For fun, here's a cleaned up version
mainly it replaces char* with std::string (since we're doing C++)
it makes the whole thing self-contained.
It uses correct input validation (don't use while (!infile.eof()), check extraction operators)
I didn't implement your Queue :)
Live On Coliru
#include <iostream>
#include <fstream>
#include <sstream>
struct House {
House()
: address(), footage(0), bedrooms(0), bathrooms(0), features()
{ }
House(std::string ad, int fo, int be, int ba, std::string fe)
: address(ad), footage(fo), bedrooms(be), bathrooms(ba), features(fe)
{ }
std::string getAddress() const { return address; }
int getFootage() const { return footage; }
int getBedrooms() const { return bedrooms; }
int getBathrooms() const { return bathrooms; }
std::string getFeatures() const { return features; }
void setAddress(std::string ad) { address = ad; }
void setFootage(int fo) { footage = fo; }
void setBedrooms(int be) { bedrooms = be; }
void setBathrooms(int ba) { bathrooms = ba; }
void setFeatures(std::string fe) { features = fe; }
friend std::ostream &operator<<(std::ostream &out, House const &house) {
return out << "Address: " << house.getAddress() << '\n'
<< "Footage: " << house.getFootage() << '\n'
<< "Bed rooms: " << house.getBedrooms() << '\n'
<< "Bath rooms: " << house.getBathrooms() << '\n'
<< "Features: " << house.getFeatures() << '\n';
}
private:
std::string address;
int footage;
int bedrooms;
int bathrooms;
std::string features;
};
struct Queue {
Queue(std::string filename);
struct Node {
House value;
Node* next;
};
Node *head, *tail;
void enqueue(House const& h) {
// TODO
std::cout << h << "\n";
}
};
Queue::Queue(std::string filename) : head(nullptr), tail(nullptr) {
std::ifstream infile(filename);
std::string address;
int footage = 0;
int bedrooms = 0;
int bathrooms = 0;
std::string features;
std::string line; // lines
while (getline(infile, address) && getline(infile, line)) {
std::istringstream iss(line);
if (iss >> footage >> bedrooms >> bathrooms && getline(iss, features)) {
enqueue(House(address, footage, bedrooms, bathrooms, features));
}
}
}
int main()
{
Queue q("data.dat");
}
For input:
Blv. Dreams Abroken 24, 78377d XG, ClassyCode
2 4 1 pool sauna porch indoor-parking
Oyi. Qernzf Noebxra 24, 78377q KT, PynfflPbqr
3 8 2 cbby fnhan cbepu vaqbbe-cnexvat
It prints the output:
Address: Blv. Dreams Abroken 24, 78377d XG, ClassyCode
Footage: 2
Bed rooms: 4
Bath rooms: 1
Features: pool sauna porch indoor-parking
Address: Oyi. Qernzf Noebxra 24, 78377q KT, PynfflPbqr
Footage: 3
Bed rooms: 8
Bath rooms: 2
Features: cbby fnhan cbepu vaqbbe-cnexvat
I'm just starting to learn object oriented programming in C++ and am having issues figuring out how to print an object that is stored inside an array. From what I know, I want to just try to try and go through the array and print out each employee object, how because objects are different than variables like int and double I'm sure it's causing a problem. Is my logic wrong, or is it just syntax? Here is my code:
Header:
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
#include <string>
using namespace std;
class Employee
{
private:
string name;
string idNumber;
string department;
string position;
int yearsWorked;
public:
Employee();
Employee(string, string);
Employee(string, string, string, string, int);
void setName(string);
void setIdNumber(string);
void setDepartment(string);
void setPosition(string);
bool setYearsWorked(int);
string getName()const;
string getIdNumber()const;
string getDepartment()const;
string getPosition()const;
int getYearsWorked()const;
};
#endif
Implementation:
#include "Employee.h"
using namespace std;
Employee::Employee()
{
string name = "";
string idNumber = "";
string department = "";
string position = "";
int yearsWorked = 0;
}
Employee::Employee(string nm, string id)
{
string name = nm;
string idNumber = id;
string department = "";
string position = "";
int yearsWorked = 0;
}
Employee::Employee(string nm, string id, string dpt, string pos, int years)
{
string name = nm;
string idNumber = id;
string department = dpt;
string position = pos;
int yearsWorked = years;
}
void Employee::setName(string nm)
{
name = nm;
}
void Employee::setIdNumber(string id)
{
idNumber = id;
}
void Employee::setDepartment(string dpt)
{
department = dpt;
}
void Employee::setPosition(string pos)
{
position = pos;
}
bool Employee::setYearsWorked(int years)
{
if (years >= 0)
{
yearsWorked = years;
return true;
}
else
return false;
}
string Employee::getName()const
{
return name;
}
string Employee::getIdNumber()const
{
return idNumber;
}
string Employee::getDepartment()const
{
return department;
}
string Employee::getPosition()const
{
return position;
}
int Employee::getYearsWorked()const
{
return yearsWorked;
}
Main:
#include <iostream>
#include <iomanip>
#include "Employee.h"
using namespace std;
const int SIZE = 3;
int main()
{
Employee emp1("Jenny Jacobs", "JJ8990", "Accounting", "President", 15);
Employee emp2("Myron Smith", "MS7571", "IT", "Programmer", 5);
Employee emp3("Chris Raines", "CR6873", "Manufacturing", "Engineer", 30);
Employee employees[SIZE] = {emp1, emp2, emp3};
for (int i = 0; i < SIZE; i++)
{
cout << employees[i] << endl;
}
system("PAUSE");
return 0;
}
Add this:
std::ostream& operator<<( std::ostream& stream, Employee const& emp )
{
return (stream << emp.getName());
}
Modify as needed.
General comments:
Do not place using namespace std; in the global namespace in a header. Keep in mind that the standard library defines very common names like distance. Which can easily lead to name collisions.
Reserve ALL UPPERCASE names for macros, to reduce the chance of name collisions and inadvertent text substitution.
Preferentially pass potentially "large" objects, such as std::string, by reference, e.g. formal argument type std::string const&, in order to avoid excessive copying. There are some exceptions to this rule when one aims for perfect code, e.g. for C++11 move semantics, but it's a good general rule.
employees[i] is of type Employee. So either you have to print like
cout<<employees[i].getName(); // so on
Or you have to overload << operator for Employee type:
ostream& operator<<(ostream& stream, Employee const& emp );
Firstly. in my machine it compiles fine
Secondly, you are doing:
string name = nm;
So name is a automatic variable, Not the member of your class. You should do like:
name = nm; // if you delete int name; line
Or,
this->name = nm;
Some changes of your code:
Employee::Employee()
: yearsWorked( 0 )
{
}
Employee::Employee(string nm, string id)
: name( nm ), idNumber( id ), yearsWorked( 0 )
{
}
Employee::Employee(string nm, string id)
: name( nm ), idNumber( id ), department( dpt ), position( pos ), yearsWorked( years ),
{
}
std::ostream & operator <<( std::ostream &os, const Employee &emp )
{
return ( os << "ID: " << emp.idNumber << ", name: " << emp.name
<< ", department: " << emp.department << ", position: " << emp.position
<< ", years worked: " << emp.yearsWorked );
}