How to debug "ISO C++ forbids declaration of 'car' with no type"? - dev-c++

I am trying to figure out why I keep getting this error on Dev C++. I don't seem to get any errors when I use computers from my school, so I was wondering if I have missed something here.
[Error] ISO C++ forbids declaration of 'car' with no type -f
permissive
Code:
#include <iostream>
#include <string>
using namespace std;
class Car //class definition
{
private: int modelYr; string model; int speed;
public:
car(int year, string brand)
{ modelYr=year; model=brand; speed=0;} //Constructor
void accelerate() {speed = speed + 5;} //accelerate +5mph (mutator)
void brake() {speed = speed - 5;} //brake -5mph (mutator)
int get_modelYr() const {return modelYr;} //returns model year (accessor)
string get_model() const {return model;} //returns model name (accessor)
int getspeed() const {return speed;} //returns current speed (accessor)
};//end of class definition (note the semicolon ;)
int main() {
Car vehicle; //create a vehicle from class Car
string carModel;//car model to be input by user
int carYear; //car year to be input by user
const string line = "\n-------------------\n"; //used to display a line
cout <<"Enter car model year (2000-current): ";
while(! (cin >> carYear) || (carYear < 2000) ) //carYear validation
{ //checking for numeric year 2000 or later
cin.clear();cin.ignore(10000,'\n');
cout<<"sorry you must enter car year 2000 or later :"<<flush;
} //while loop validation ends
cout <<"Enter car model (example: GMC): "; cin >> carModel;
vehicle.car(carYear,carModel);
cout << line << "Starting speed for your " << vehicle.get_modelYr()
<< " " << vehicle.get_model() << " is " << vehicle.getspeed() << " mph" <<line;
for(int count=0;count<5;count++) //accelerate five times
{ vehicle.accelerate();
cout << "***ACCELERATING***\nSpeed is currently:"<< vehicle.getspeed() << endl;
}//end acceleration
for ( int count=0;count<5 ;count++ )
{vehicle.brake();
cout << "***BRAKING***\nSpeed is currently: " << vehicle.getspeed() << endl;
}
cout << line << "Ending speed for your " << vehicle.get_modelYr()
<< " " << vehicle.get_model() << " is " << vehicle.getspeed() <<" mph"<< line;
return(0);
}//end of main program

Your constructor must be named the same as your class.
#include <iostream>
#include <string>
using namespace std;
class Car //class definition
{
private: int modelYr; string model; int speed;
public:
Car(int year, string brand)
{ modelYr=year; model=brand; speed=0;} //Constructor
void accelerate() {speed = speed + 5;} //accelerate +5mph (mutator)
void brake() {speed = speed - 5;} //brake -5mph (mutator)
int get_modelYr() const {return modelYr;} //returns model year (accessor)
string get_model() const {return model;} //returns model name (accessor)
int getspeed() const {return speed;} //returns current speed (accessor)
};//end of class definition (note the semicolon ;)
int main() {
Car vehicle; //create a vehicle from class Car
string carModel;//car model to be input by user
int carYear; //car year to be input by user
const string line = "\n-------------------\n"; //used to display a line
cout <<"Enter car model year (2000-current): ";
while(! (cin >> carYear) || (carYear < 2000) ) //carYear validation
{ //checking for numeric year 2000 or later
cin.clear();cin.ignore(10000,'\n');
cout<<"sorry you must enter car year 2000 or later :"<<flush;
} //while loop validation ends
cout <<"Enter car model (example: GMC): "; cin >> carModel;
vehicle.car(carYear,carModel);
cout << line << "Starting speed for your " << vehicle.get_modelYr()
<< " " << vehicle.get_model() << " is " << vehicle.getspeed() << " mph" <<line;
for(int count=0;count<5;count++) //accelerate five times
{ vehicle.accelerate();
cout << "***ACCELERATING***\nSpeed is currently:"<< vehicle.getspeed() << endl;
}//end acceleration
for ( int count=0;count<5 ;count++ )
{vehicle.brake();
cout << "***BRAKING***\nSpeed is currently: " << vehicle.getspeed() << endl;
}
cout << line << "Ending speed for your " << vehicle.get_modelYr()
<< " " << vehicle.get_model() << " is " << vehicle.getspeed() <<" mph"<< line;
return(0);
}//end of main program

Related

The code compiles it does not read staff.txt

The code compiles it does not read staff.txt. Not sure how to fix in the code. the error must be in reading the staff.txt of the code. Does anyone have an idea? output is in the image provided. Background on the question:
You are tasked to create 2 ADTs: customers and staff. Each customer will have a first and last name, an indication if the customer is enrolled in the “preferred” program, the car they are driving, and the amount of money owed to the company. On the other hand, each staff member will have a first and last name, the car they are driving, and their salary. In a real-world problem, there would obviously be more records associated with each staff member and customer.
ODU rentals would like you to automatically process txt files and print the information to the console screen. When you perform this process, ensure that your member variables are private. In addition, be sure to use getter and setter functions to manipulate and print your data. You may print your data in any format as long as it is organized. An example of correct output can be seen below.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cstdlib>
using namespace std;
class Customer {
string fname;
string lname;
int enroll;
string car;
float amount;
public:
//Defining the customer ADT
Customer();
void setFirstName(string fnm);
void setLastName(string lnm);
void setEnroll(int e);
void setCarName(string cnm);
void setAmount(float amt);
string getFirstName();
string getLastName();
int getEnroll();
string getCarName();
float getAmount();
void printData();
};
Customer::Customer() {
fname = lname = car = "";
enroll = 0;
amount = 0;
}
void Customer::setFirstName(string fnm) {
fname = fnm;
}
void Customer::setLastName(string lnm) {
lname = lnm;
}
void Customer::setEnroll(int e) {
enroll = e;
}
void Customer::setCarName(string cnm) {
car = cnm;
}
void Customer::setAmount(float amt) {
amount = amt;
}
string Customer::getFirstName() {
return(fname);
}
string Customer::getLastName() {
return(lname);
}
int Customer::getEnroll() {
return(enroll);
}
string Customer::getCarName() {
return(car);
}
float Customer::getAmount() {
return(amount);
}
void Customer:: printData() {
cout << left << setw(25) << getFirstName()+" "+getLastName() << left <<setw(15) << getEnroll();
cout << left << setw(15) << getCarName() << left << setw(15) << fixed << setprecision(2) << getAmount() << endl;
}
class Staff {
string fname;
string lname;
string car;
float salary;
public:
//Defining staff ADT
Staff();
void setFirstName(string fnm);
void setLastName(string lnm);
void setCarName(string cnm);
void setSalary(float sal);
string getFirstName();
string getLastName();
string getCarName();
float getSalary();
void printData();
};
Staff::Staff() {
fname = lname = car = "";
salary = 0;
}
void Staff::setFirstName(string fnm) {
fname = fnm;
}
void Staff:: setLastName(string lnm) {
lname = lnm;
}
void Staff::setCarName(string cnm) {
car = cnm;
}
void Staff::setSalary(float sal) {
salary = sal;
}
string Staff::getFirstName() {
return(fname);
}
string Staff::getLastName() {
return(lname);
}
string Staff::getCarName() {
return(car);
}
float Staff::getSalary() {
return(salary);
}
void Staff:: printData() {
cout << left << setw(25) << getFirstName()+" "+getLastName() << left << setw(15);
cout << getCarName() << left << setw(15) << fixed << setprecision(2) << getSalary() <<endl;
}
//Main function
//Read txt files
int main() {
string fnm, lnm, carnm;
float amt, sal;
int e, i=0, recno;
ifstream fstaff("staff.txt");
if(!fstaff) {
cout << "File can not be opened" << endl;
exit(1);
}
fstaff >> recno;
Staff s[recno];
cout << left<<setw(25) << "Name" << left << setw(15) << "Car" << left << setw(15) << "Salary" <<endl;
cout << "____________________________________________________________________________" << endl;
for(i=0; i<recno; i++) {
fstaff>>fnm>>lnm>>carnm>>sal;
s[i].setFirstName(fnm);
s[i].setLastName(lnm);
s[i].setCarName(carnm);
s[i].setSalary(sal);
s[i].printData();
}
fstaff.close();
ifstream fcust("customers.txt");
if(!fcust) {
cout << "File can not be opened"<<endl;
exit(1);
}
fcust >> recno;
Customer c[recno];
cout << endl << endl;
cout << left << setw(25) << "Name" << left << setw(15) << "Preferred" << left << setw(15) << "Car" << left << setw(15) << "Bill" << endl;
cout <<"____________________________________________________________________________"<<endl;
for(i=0; i<recno; i++) {
fcust >> fnm >> lnm >> e >> carnm >>amt;
c[i].setFirstName(fnm);
c[i].setLastName(lnm);
c[i].setEnroll(e);
c[i].setCarName(carnm);
c[i].setAmount(amt);
c[i].printData();
}
fcust.close();
return 1;
}
Code Output

I cannot use the static variable [duplicate]

This question already has answers here:
Undefined reference to a static member
(5 answers)
Closed 1 year ago.
I'm trying to print the employee count after each created object but I'm getting an error like this: undefined reference to `Employee::numberofEmployees'. How can I solve this little problem? Any ideas? Btw I'm using a local class.
the purpose of the numberofEmployees variable is to store the information on the number of employee objects created/instantiated so far.
#include <iostream>
#include <string>
using namespace std;
class Employee{
public:
string name;
string surname;
int year;
double salary;
static int numberofEmployees;
Employee(int yil,string isim,string soyisim): year(yil),name(isim),surname(soyisim){
numberofEmployees++;
}
Employee(){
name = "not-set";
year = 0;
surname = "not-set";
salary = 0.0;
}
void calculateSalary(){
salary = 2310 + 2310 * year * 12 / 100.0;
}
void printInfo(){
cout << name << " " << surname << " " << "(" << year << ")" << " " << salary << "TL/month" << endl;
}
};
int main()
{
Employee person1(4,"Berk","Kandemir");
cout << Employee::numberofEmployees << endl;
Employee person2(8,"Esat","Kandemir");
cout << Employee::numberofEmployees << endl;
Employee person3(20,"Paul","Walker");
cout << Employee::numberofEmployees << endl;
person1.calculateSalary();
person2.calculateSalary();
person3.calculateSalary();
person1.printInfo();
person2.printInfo();
person3.printInfo();
return 0;
}
You have to initialize your static data member outside the class using scope resolution operator something like this.
int Employee::numberofEmployees = 0;
This shows that you are accessing a static variable of class Employee and then initializing it.
If you have a static variable within a class, you are supposed to initialise it outside of the class, ie in a .cpp file. From C++17, however, you are allowed to initialise it in-class, in-line, using the inline keyword.
Code:
#include <string>
#include <iostream>
using namespace std;
class Employee
{
public:
string name;
string surname;
int year;
double salary;
static inline int numberofEmployees = 0;
Employee(int yil, string isim, string soyisim) : year(yil), name(isim), surname(soyisim)
{
numberofEmployees++;
}
Employee()
{
name = "not-set";
year = 0;
surname = "not-set";
salary = 0.0;
}
void calculateSalary()
{
salary = 2310 + 2310 * year * 12 / 100.0;
}
void printInfo()
{
cout << name << " " << surname << " "
<< "(" << year << ")"
<< " " << salary << "TL/month" << endl;
}
};
int main()
{
Employee person1(4, "Berk", "Kandemir");
cout << Employee::numberofEmployees << endl;
Employee person2(8, "Esat", "Kandemir");
cout << Employee::numberofEmployees << endl;
Employee person3(20, "Paul", "Walker");
cout << Employee::numberofEmployees << endl;
person1.calculateSalary();
person2.calculateSalary();
person3.calculateSalary();
person1.printInfo();
person2.printInfo();
person3.printInfo();
return 0;
}
Or keep your code and add:
int Employee::numberofEmployees = 0;
After your class.
Output:
1
2
3
Berk Kandemir (4) 3418.8TL/month
Esat Kandemir (8) 4527.6TL/month
Paul Walker (20) 7854TL/month

How to pass an object(type a) to a private object(type a) of another object(type b) through function of friend

#include <iostream>
#include <vector>
using namespace std;
class Flight;
class Time {
private :
int hour;
int minute;
public :
Time(int hour,int minute){
this->hour = hour;
this->minute = minute;
};
int getHour(){
return hour;
}
int getMinute(){
return minute;
}
};
class Passenger{
private:
string name;
int age;
public :
Passenger(string name , int age){
this->name = name;
this->age = age;
}
void printDetails(){
cout << "Name: " << name << "\t";
cout << "Age: " << age <<"\t";
}
friend void addPassenger(Passenger *p,int num,Flight f);
friend Flight;
};
class Flight {
private :
string id;
string destination;
Time *depart;
Time *arrival;
vector<Passenger> passengerList;
Passenger *pass;
public :
Flight(string id, string destination, Time *t, Time *a){
this->id = id;
this->destination = destination;
depart = t;
arrival = a;
id = 3;
};
void printInfo(){
cout<< "Flight Number : " << id << endl;
cout<< "Destination : " << destination << endl;
cout<< "Desparture : " << depart->getHour() << ":" << depart->getMinute()<< endl;
cout<< "Arrival : " << arrival->getHour() << ":" << arrival->getMinute() << endl;
}
void printList(){
cout << pass->name[0];
}
friend class Passenger;
friend void addPassenger(Passenger *p,int num,Flight f);
};
void addPassenger(Passenger *p,int num,Flight f){
// for(int i=0;i<num;i++){
// f.passengerList.push_back(p[i]);
f.pass->name = p->name;
// }
}
int main(){
int num_passenger;
int temp_age;
string temp_name;
vector<int> passenger_age;
vector<string> passenger_name;
Time t(2,4);
Time t2(2,3);
Flight ff("3","4",&t,&t2);
cout<< "Enter the number of passenger" << endl;
cin>> num_passenger;
cout<< endl;
Passenger *pas[num_passenger];
for(int i=0;i < num_passenger; i++){
cout<< "Enter the name of adult "<< i+1 << endl;
cin>> temp_name;
passenger_name.push_back(temp_name);
cout<< "Enter the age of adult "<< i+1 << endl;
cin>> temp_age;
passenger_age.push_back(temp_age);
}
for(int p=0; p < num_passenger; p++){
pas[p] = new Passenger(passenger_name[p],passenger_age[p]);
}
addPassenger(*pas,2,ff);
ff.printList();
return 0;
}
I need to pass array object of Passenger Class into private array object of Passenger Class that inside object of Flight Class through function addPassenger.
Everything compile fine, but I can't get printList(object Flight) work, it simply jumps out and terminates the console.
Sorry it quite complicated due to requirement of project.
Hope to have some helps, Thanks.
Problem 1
The main problem is at line
f.pass->name = p->name;
The source of the problem is that the member variable pass of Flight is not initialized properly and then you go on to use f.pass as though it is a valid pointer.
Problem 2
The function addPassenger takes a Flight object as input. When you call the function, the function gets a copy of the original Flight object. Any changes made to the Flight object in addPassenger are to the local copy, not the object from main.
With the following changes, I was able to run your program without any problem.
Changed the member of variable of Flight to:
string id;
string destination;
Time *depart;
Time *arrival;
vector<Passenger> passengerList;
Removed the member varible pass.
Changed the signature of addPassenger to.
void addPassenger(std::vector<Passenger> const& plist, Flight& f);
and changed its implementation to
void addPassenger(std::vector<Passenger> const& plist, Flight& f)
{
for(auto& p : plist ){
f.passengerList.push_back(p);
}
}
Changed the implementation of Flight::printList to:
void printList(){
for(auto& p : passengerList ){
cout << p.name << endl;
}
}
Changed the type of pas in main to:
std::vector<Passenger> pas;
Other things needed to be changed to account for these changes. Here's the complete program:
#include <iostream>
#include <vector>
using namespace std;
class Flight;
class Time {
private :
int hour;
int minute;
public :
Time(int hour,int minute){
this->hour = hour;
this->minute = minute;
};
int getHour(){
return hour;
}
int getMinute(){
return minute;
}
};
class Passenger{
private:
string name;
int age;
public :
Passenger(string name , int age){
this->name = name;
this->age = age;
}
void printDetails(){
cout << "Name: " << name << "\t";
cout << "Age: " << age <<"\t";
}
friend void addPassenger(std::vector<Passenger> const& plist, Flight& f);
friend Flight;
};
class Flight {
private :
string id;
string destination;
Time *depart;
Time *arrival;
vector<Passenger> passengerList;
public :
Flight(string id, string destination, Time *t, Time *a){
this->id = id;
this->destination = destination;
depart = t;
arrival = a;
id = 3;
};
void printInfo(){
cout<< "Flight Number : " << id << endl;
cout<< "Destination : " << destination << endl;
cout<< "Desparture : " << depart->getHour() << ":" << depart->getMinute()<< endl;
cout<< "Arrival : " << arrival->getHour() << ":" << arrival->getMinute() << endl;
}
void printList(){
for(auto& p : passengerList ){
cout << p.name << endl;
}
}
friend class Passenger;
friend void addPassenger(std::vector<Passenger> const& plist, Flight& f);
};
void addPassenger(std::vector<Passenger> const& plist, Flight& f)
{
for(auto& p : plist ){
f.passengerList.push_back(p);
}
}
int main(){
int num_passenger;
int temp_age;
string temp_name;
vector<int> passenger_age;
vector<string> passenger_name;
Time t(2,4);
Time t2(2,3);
Flight ff("3","4",&t,&t2);
cout<< "Enter the number of passenger" << endl;
cin>> num_passenger;
cout<< endl;
std::vector<Passenger> pas;
for(int i=0;i < num_passenger; i++){
cout<< "Enter the name of adult "<< i+1 << endl;
cin>> temp_name;
passenger_name.push_back(temp_name);
cout<< "Enter the age of adult "<< i+1 << endl;
cin>> temp_age;
passenger_age.push_back(temp_age);
}
for(int p=0; p < num_passenger; p++){
pas.push_back(Passenger(passenger_name[p],passenger_age[p]));
}
addPassenger(pas, ff);
ff.printList();
return 0;
}
See it working at http://ideone.com/Chttoe.

C++ getting ofstream access error when passed to a function

For some reason the ofstream out with the iterator at the bottom is denying access to itself for some reason, something having to do with the pointer? Honestly, me and my friends have been trying to figure out what is wrong here for a long time. Even a veteran who has been coding for years couldn't help me. Any help is appreciated! here is the error:
Error 6 error C2248: 'std::basic_ofstream<_Elem,_Traits>::basic_ofstream' : cannot access private member declared in class 'std::basic_ofstream<_Elem,_Traits>'
as well as intellisense
7 IntelliSense: "std::basic_ofstream<_Elem, _Traits>::basic_ofstream(const std::basic_ofstream<_Elem, _Traits>::_Myt &_Right) [with _Elem=char, _Traits=std::char_traits]" (declared at line 1034 of "C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\include\fstream") is inaccessible
/*
estimate.cc -- Program to estimate the cost of attendance for students -- Part 1
This part will read the records, place them in separate vectors, sort them,
and then write them out to separate files.
Authors: Larry Morell,
Aaron Wilson
Strategy:
Create a class for a general student called Student
Divide students into three categories: Resident, Commuter, Onliner.
Set up a class for each one of these categories to inherit from Student.
The input file is called students.dat. Its format is as follows.
HourlyRate Fees CentsPerMile -- first line
The remaining lines are one of three formats, one line for each student
R FirstName LastName GPA HoursRegistered Major MealPlan Housing -- for resident student
C FirstName LastName GPA HoursRegistered Major Miles MealPlan -- for commuter student
O FirstName LastName GPA HoursRegistered Major ISP_Cost -- for onliner student
Modification History
Date Action
10/30/15 -- Original version
11/18/15 -- vectors program
12/1/15 -- polymorphism, changing it to use only one vector and pointers
*/
using namespace std;
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>
class Student {
protected:
string first, last; // First and laast name
float gpa; // Grade point average
int hoursRegistered; // Number of hours registered for next semester
string major; // Declared major or "Undeclared
static float hourlyRate; // What the college charges per credit hour
static float fees; // The flat fees charged to each student
static float costPerMile; // Cost per mile for travel
public:
// Constructors
Student() {
first = "Unknown";
last = "Person";
gpa = 0.0;
hoursRegistered = 0;
}
Student(string fn, string ln, float gpa, int hours ) {
this->first = fn;
this->last = ln;
this->gpa = gpa;
this->hoursRegistered = hours;
}
// Setters
static void setHourlyRate(float hr) { hourlyRate = hr; }
static void setFees(float f) { fees = f; }
static void setCostPerMile(float cpm) { costPerMile = cpm; }
// Getters
string getMajor() const { return major; }
string getName() const { return first + ' ' + last; }
string getFirst() const { return first; }
string getLast() const { return last; }
int getHoursRegistered() const { return hoursRegistered; }
float getBookCost() const { return 30.00*hoursRegistered ;}
// Input routine
bool read(istream &in) {
in >> first >> last >> gpa >> hoursRegistered >> major;
return in;
}
// Output routine
void write (ostream &out) {
out << first << ' ' << last << ' '
<< gpa << ' ' << hoursRegistered
<< ' ' << major;
}
// estimate -- determine the cost of attending next semester
virtual void estimate(ofstream thisOut)
{
}
};
// Declare location of static variables as globals as required by C++
// These are variables that are shared by all instances of class Student
// and its descendants
float Student::hourlyRate;
float Student::fees;
float Student::costPerMile;
// Class Resident -- extends Student
class Resident : public Student {
protected:
float mealPlan;
float housing;
public:
bool read(istream &in) {
Student::read(in);
in >> mealPlan >> housing;
return in;
}
void write (ostream &out) {
Student::write(out); // Call the write routine inherited from Student
out << ' ' << mealPlan << ' ' << housing;
}
virtual void estimate(ofstream thisOut) {
thisOut << "Dear " + first + ' ' + last + ',' << endl << endl << "You are registered for " << hoursRegistered << " hours. Your costs for the upcoming year have been calculated as follows:" << endl;
thisOut << "Tuition: " << fixed << '$' << (hoursRegistered * hourlyRate) << endl;
thisOut << (hoursRegistered * hourlyRate) + fees + mealPlan + housing;
}
};
// Class Commuter -- extends Student
class Commuter : public Student {
private:
// Must contain miles , mealplan
float miles;
float mealplan;
public:
bool read(istream &in) {
Student::read(in);
in >> mealplan >> miles;
return in;
}
void write (ostream &out) {
Student::write(out);
out << ' ' << mealplan << ' ' << miles;
}
virtual void estimate(ofstream thisOut) {
thisOut << "Dear " + first + ' ' + last + ',' << endl << endl << "You are registered for " << hoursRegistered << " hours. Your costs for the upcoming year have been calculated as follows:" << endl;
thisOut << "Tuition: " << fixed << '$' << (hoursRegistered * hourlyRate) << endl;
thisOut << (hoursRegistered * hourlyRate) + (miles * costPerMile) + fees + mealplan;
}
};
// Class Onliner -- extends Student
class Onliner : public Student {
private:
// Must contain ispcost
float ispcost;
public:
bool read(istream &in) {
Student::read(in);
in >> ispcost;
return in;
}
void write (ostream &out) {
Student::write(out);
out << ispcost;
}
virtual void estimate(ofstream thisOut)
{
thisOut << "Dear " + first + ' ' + last + ',' << endl << endl << "You are registered for " << hoursRegistered << " hours. Your costs for the upcoming year have been calculated as follows:" << endl;
thisOut << "Tuition: " << fixed << '$' << (hoursRegistered * hourlyRate) << endl;
thisOut << (hoursRegistered * hourlyRate) + fees + ispcost;
}
};
// compareStudents -- returns whether or not s1 is less than s2
bool compareStudents(Student* s1, Student* s2) {
return s1 -> getLast() < s2 -> getLast();
}
int main () {
// Declare locals for holding input
ifstream in ("students.dat");
float hourlyRate, fees, costPerMile;
// Read and store the hourly rate, fees and cost per mile
in >> hourlyRate >> fees >> costPerMile;
Student::setHourlyRate(hourlyRate);
Student::setFees(fees);
Student::setCostPerMile(costPerMile);
// Read student records from the input file
char studentType;
vector <Student *> studentVector;
while (in >> studentType) {
if (studentType == 'R') {
Resident *r = new Resident;
r -> read(in);
studentVector.push_back(r);
}
else if(studentType == 'C') {
Commuter *c = new Commuter;
c->read(in);
studentVector.push_back(c);
}
else if(studentType == 'O') {
Onliner *o = new Onliner;
o->read(in);
studentVector.push_back(o);
}
else { // These two lines will need to be replaced
cout << "error: data in file is not correct" << endl;
}
}
// Sort the entire resident list using the supplied comparison routine
sort(studentVector.begin(), studentVector.end(), compareStudents);
// Write the vectors to their respective files
ofstream out;
out.open("students.dat");
for (auto ptr: studentVector) {
ptr -> estimate(out);
}
out.close();
return 0;
}
You're passing the stream by value into the function, but streams cannot be copied.
Define the function as
virtual void estimate(ofstream& thisOut)
instead.
There are also a few places where you need to replace return in with return in.good() (or static_cast<bool>(in)) for compatibility with C++11 and later.

Setting a string value to none when a class related to it is deleted

I need help with something which I believe is simple. I can assign a student to a project. But when I delete the project, the student is still keeping the project name. I'm thinking of just renaming it back to "None" but I have no idea on how to do that. Help?
Edit
map<int, Student> mstore and vector<int> storeid added.
#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
#include <map>
using namespace std;
class Human {
public:
virtual void print() const = 0;
};
class Student : public Human {
protected:
string studname;
int studId;
string project;
public:
Student();
Student (string studname, int studId) : studname("Unknown"), studId(0), project("None")
{
cout << "A student is created: Name = " << studname
<< ". Id = " << studId << endl;
}
virtual void print() const {
cout << "Name = " << studname << ". Id = " << studId << ". Project = " << project <<endl; }
void setSName (string sname) { studname = sname; }
void setSID (int sID) { studId = sID; }
void printStudentInfo() const;
void printStudentInfoline() const;
};
void Student::printStudentInfo() const
{
cout << "\nStudent name: " << studname << endl;
cout << "Student ID: " << studId << endl;
cout << "Project: " << project << endl;
}
void Student::printStudentInfoline() const
{
cout << studId << ", " << studname << ", " << project << endl;
}
class Project {
protected:
string projname;
public:
vector <Student> students;
vector <int> storeid;
Project (string projname) : projname(projname) { cout << "Project " << projname << " created" << endl;}
void setPName (string projname) { this->projname = projname; }
void add (int& sid)
{
//student.setProject (projname);
storeid.push_back(sid);
}
int returnid(int& a)
{
return storeid[a];
}
int returnsize()
{ return storeid.size(); }
void printproj() const {
cout << endl << projname << " list: \n";
cout << "Student(s) : " << endl;
for (int i = 0; i < storeid.size(); i++){
cout << storeid[i] << endl;
}
}
void printprojname() const {
cout << projname << endl;
}
};
int main() {
string StudentName;
string ProjectName;
int Studentid;
Student *s1;
Project *p1;
vector<Student> store;
vector<Project> projstore;
map<int, Student> mstore;
map<int, Student>::const_iterator itr;
for (int n=0; n<3; n++) //loop to create 3 students
{
cout <<"Enter name : ";
getline(cin, StudentName);
cout <<"Enter ID : ";
cin >> Studentid;
s1 = new Student(StudentName, Studentid);
s1->setSName(StudentName);
s1->setSID(Studentid);
store.push_back(*s1);
mstore.insert(make_pair(Studentid, *s1));
cin.get();
}
//print map
for(itr=mstore.begin(); itr!=mstore.end() ;++itr)
itr->second.printStudentInfo();
//itr=mstore.begin()+2;
//itr.print();
cout << "Enter project name: ";
getline(cin, ProjectName);
p1 = new Project(ProjectName);
p1->setPName(ProjectName);
//Assigning student to project
cout << endl;
cout << "How many students? :" ;
int y;
cin >> y;
for ( int i = 0; i < y; i++){
cout << "Who would you like to add to this project?" << endl;
int x = 1;
for(itr=mstore.begin(); itr!=mstore.end() ;++itr)
itr->second.printStudentInfoline();
int insID;
cout << "Enter ID number: ";
cin >> insID;
p1->add(insID);
/*
for ( it = store.begin(); it != store.end(); ++it ) {
// For each friend, print out their info
cout << x << ". ";
it->printStudentInfoline();
x++;
}
x = 1;
int insS;
cout << "Enter number: ";
cin >> insS;
p1->add(store[(insS-1)]); //stores selected student into the object
*/
cout << "\nAdding Student done\n" << endl;
}
projstore.push_back(*p1);
//Mstore finds for related ids and displays them accordingly
cout << "print project"<< endl;
vector<Project>::iterator pt;
for ( pt = projstore.begin(); pt != projstore.end(); ++pt ) {
pt->returnsize();
for (int i=0; i <pt->returnsize(); i++){
cout << pt->returnid(i) << endl;
itr=mstore.find(pt->returnid(i));
itr->second.printStudentInfo();
}
}
cout << endl;
cout << "Deleting project" << endl;
cout << "What would you like to remove?" << endl;
int x = 1;
//storeid will display ids. How do I link them to `store` map?
for ( pt = projstore.begin(); pt != projstore.end(); ++pt ) {
cout << x << ". ";
pt->printprojname();
x++;
}
//Now to delete the selected project
int delP;
cout << "Enter number: ";
cin >> delP;
cin.ignore();
system("pause");
projstore.erase(projstore.begin()+delP-1);
// Students
cout << "\n Current students" << endl;
for(itr=mstore.begin(); itr!=mstore.end() ;++itr)
itr->second.printStudentInfo();
}
Look at how you add a Student to a Project:
void add (Student& student)
{
student.setProject (projname);
students.push_back (student); // <-- AHA!
}
First you assign the Project name to the Student, then the Project stores a copy of the Student. After that, the Project has no link to the original Student, and can't inform him/her of its own demise when the time comes.
You'll have to rethink this design; there are three major options: 1) the Students can look up their respective Projects in the store, 2) the Project can look up its Students in the students vector, or 3) the Project owns the Students (in which case they should probably be GraduateStudents).
EDIT:
If that's the way you want to do it, use map<int, Student> store to store the Students, using ID number as an index. Then a Project can have a vector<int> (or set<int>) of student ID numbers. It can look Students up in the store with ease.
EDIT:
To print out the entire collection of students:
for(map<int, Student>::const_iterator itr=store.begin(); itr!=store.end() ;++itr)
itr->second.print();
EDIT:
If the Project has a vector<int> of student ID numbers, then what argument do you think Project::add(?) should take?
EDIT:
The Project can act on a Student by means of the student ID number and access to mstore:
// in Project:
mstore[id].whatever()
EDIT:
Sometimes asking the right question -- or in this case, phrasing the question correctly -- is half the battle. 'Now how do I change "None" to the inserted project name?' A better way to put it is 'How does the Project change one of its Student's project from "None" to projname?' Once you put it that way, the answer is almost obvious:
// in Project:
mstore[id].setSProject(projname);
Note that Student does not yet have setSProject(string), you'll have to add it. Also, note that this solution is not ideal since 1) anybody can change a Student's project, and 2) a Student's project need not actually be the name of a real Project. There is more than one way to deal with these problems.