Address Book using Inheritance and Operator Overloading or Exception handling - c++

I have to make an address book using C++ and should include classes and inherited classes. The main class contains name and address and the inherited Teacher class contains teacher Phone number and CNIC and Employee class contains Phone and CNIC and the Student class contains student ID and Phone. I made a program in C++ but that would always over write the previous data. I am stuck here. I would need a skull program or simple algorithms to guide me ahead.
This is my code.
// new.cpp : Defines the entry point for the console application.
// Address Book.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
#include<string>
#include <conio.h>
#include <fstream>
#include <sstream>
#include <iomanip>
using namespace std;
class Main
{
private:
string Name;
string Address;
char test;
public:
virtual void getdata()
{
ofstream outfile("TEMP.txt");
cout <<"Enter Name: " ;
cin>>test;
getline(cin, Name); //cin >> Name;
cout << endl;
cout << "Enter Address: ";
getline(cin, Address);// cin >> Address;
outfile << Name
<< endl
<< Address;
}
virtual void setdata()
{
cout << "\n\nName: " << test+Name;
cout << "\nAddress: " << Address;
}
virtual void remove()
{
}
};
//----------------------------------------------------------
class Teacher : public Main
{
private:
int T_Number;
string T_CNIC;
public:
void getdata()
{
ofstream outfile("Teacher.txt");
Main::getdata();
cout << "Enter CNIC: ";
getline(cin,T_CNIC);//cin >> T_CNIC;
cout << "Enter Contact Number: " << endl;
cin >> T_Number;
outfile << T_CNIC
<< endl
<< T_Number;
cout << "Data entered" << endl;
}
void setdata()
{
Main::setdata();
cout << "\nTeacher CNIC: " << T_CNIC;
cout << "\nTeacher Contact Number: " << T_Number;
}
};
//------------------------------------------------------------
class Student : public Main
{
private:
int S_Number;
int S_ID;
public:
void getdata()
{
ofstream outfile("Student.txt");
Main::getdata();
cout << "Enter ID: ";
cin >> S_ID;
cout << "Enter Contact Number: ";
cin >> S_Number;
outfile << S_ID
<< endl
<< S_Number;
cout << "Data entered" << endl;
}
void setdata()
{
Main::setdata();
cout << "\nStudent Unique ID: " << S_ID;
cout << "\nStudent Contact Number: " << S_Number;
}
};
class Employee : public Main
{
private:
int E_Number;
string E_CNIC;
public:
void getdata()
{
ofstream outfile("Employee.txt");
Main::getdata();
cout << "Enter Employee CNIC: ";
getline(cin,E_CNIC);//cin >> E_CNIC;
cout << "Enter Contact Number: ";
cin >> E_Number;
outfile << E_CNIC
<< endl
<< E_Number;
cout << "Data entered" << endl;
;}
void setdata()
{
Main::setdata();
cout << "\nEmployee Unique ID: " << E_CNIC;
cout << "\nEmployee Contact Number: " << E_Number;
}
};
//-----------------------------------------------------------------------------------------
int _tmain(int argc, _TCHAR* argv[])
{
Main* myarr[100];
int var = 0;
int choice;
char input;
start:
printf("===============MAIN MENU===============");
printf("\n[1]Insert\n[2]Search\n[3]Delete\n[4]Exit\n");
printf("=======================================");
printf("\n\nEnter Your Choice: ");
cin >> choice;
switch(choice)
{
case 1:
cout << "\nEnter data for Student or Teacher or Employee (s/t/e)? ";
cin >> input;
do
{
if( input=='t' )
myarr[var] = new Teacher;
else if (input == 'e')
myarr[var] = new Employee;
else
myarr[var] = new Student;
myarr[var++]->getdata();
cout << " Enter another (y/n)? ";
cin >> input;
if(input == 'n')
{
goto start;
}
}
while( input =='y');
for(int j=0; j<var; j++)
myarr[j]->setdata();
cout << endl;
break;
case 2:
return 0;
break;
case 3:
return 0;
break;
case 4:
cout << "Are you sure you want to quit? " << endl;
getch();
break;
default:
cout << "Choose from 1 - 4 ONLY!!" << endl;
goto start;
break;
}
return 0;
}

Then I would try declared it protected, and instead of calling main::getdata(), you directly write data into the file. see if that works.

Related

How can i save arrays and print them on C++

How can i save arrays and print them in c++,here's what i mean, i am creating a student database, and in one class i am giving the students name, surname, id, age, etc. So how can i save them and print those information that i have given. Here is what i have tried so far, and it hasn't been working any body have any ideas?
#ifndef Student_h
#define Student_h
class Student
{
public:
virtual void Print() = 0;
};
#endif
#include "Student.h"
#ifndef University_h
#define University_h
class University :public Student
{
private:
string University_Name;
public:
University(string Uni);
void Set_University_Name(string University);
string Get_University_Name();
void Print();
};
#include<iostream>
#include<string>
#include"University.h"
#include"Student.h"
using namespace std;
University::University(string Uni)
{
Set_University_Name(Uni);
}
void University::Set_University_Name(string U_Name)
{
University_Name = U_Name;
}
string University::Get_University_Name()
{
return University_Name;
}
void University::Print()
{
cout << "\n South East European University" << University_Name;
}
class Data_Base
{
private:
string Student_Name;
string Student_Surname;
string Course;
int Student_Age;
int Student_ID;
public:
void Set_Name(string Name);
string Get_Name();
void Set_Surname(string Surname);
string Get_Surname();
void Set_Course(string _Course);
string Get_Course();
void Set_Age(int Age);
int Get_Age();
void Set_ID(int ID);
int Get_ID();
void Print();
void Print_Data();
double Average();
};
void Data_Base::Print(){
int n = 0;
cout << "\n Enter how many students you wish to add: ";
cin >> n;
for (int i = 0; i < n; i++) {
cout << "\n Student:" << i + 1 << endl;
cout << "\n Enter Student Name:";
cin >> Student_Name;
cout << "\n Enter Student Surname:";
cin >> Student_Surname;
cout << "\n What Course is the Student Studying:";
cin >> Course;
cout << "\n Enter Student Age:";
cin >> Student_Age;
cout << "\n Enter Student ID:";
cin >> Student_ID;
}
}
void Data_Base::Print_Data(){
cout << "Student Data Base: " << endl;{
cout << "\n Student Name :" << Student_Name;
cout << "\n Course :" << Course;
cout << "\n ID : " << Student_ID;
}
}
#include<iostream>
#include<string>
#include"Student.h"
#include"University.h"
#include"DataBase.h"
using namespace std;
int main()
{
int Menu;
Data_Base add, view, average;
Data_Base* AddStudent = &add;
Data_Base* ViewStudents = &view;
Data_Base* AverageGrade = &average;
menu:
cout << "\n===========================" << endl;
cout << "\n Press - 1 - To Add New Students";
cout << "\n Press - 2 - To View Added Students";
cout << "\n Press - 3 - To To Find the Average Grade";
cout << "\n Press - 0 - To Quit Program";
cout << "\n ----Please Select An Option----";
cin >> Menu;
switch (Menu)
{
case 1:
AddStudent->Print();
break;
case 2:
ViewStudents->Print_Data();
break;
case 3:
AverageGrade->Average();
break;
case 0:
return 0;
cout << "\n Thank You for Using our Program!";
break;
default:
cout << "\n Wrong Button!Try Again";
goto menu;
break;
}
return 0;
}
int main()
{
int Menu;
Data_Base db;
menu:
cout << "\n===========================" << endl;
cout << "\n Press - 1 - To Add New Students";
cout << "\n Press - 2 - To View Added Students";
cout << "\n Press - 3 - To To Find the Average Grade";
cout << "\n Press - 0 - To Quit Program";
cout << "\n ----Please Select An Option----";
cin >> Menu;
switch (Menu)
{
case 1:
db.Print();
break;
case 2:
db.Print_Data();
break;
case 3:
db.Average();
break;
case 0:
return 0;
cout << "\n Thank You for Using our Program!";
break;
default:
cout << "\n Wrong Button!Try Again";
goto menu;
break;
}
return 0;
}
This should let you see one student after you added it. As mentioned in the comments, you will need a list in order to store multiple students in the same database. Also it was wrong to use three diferent Data_base objects hoping for them to have the same private members becouse they have different memory unless they point to the same object.

expected primary-expression before 'int'- How can I sort out the problem?

I'm creating a database for Customer in C++. The firt void works well but the second one returns me the following error: expected primary-expression before 'int'
Where is teh mistake? How can I figure out it?
I can't understand why I receive this error. I'm a beginner and this is my firt important project.
Many thanks!!!
#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <cstdio>
using namespace std;
class DataCustomer{ //initialize a class
public:
DataCustomer(){
count = 0 ;
}
void AddCustomer();
void DisplayAll(int i);
void DeleteFile();
void EditFile();
void quit();
void search();
void searchName();
void searchSurname();
void searchCell();
void searchEmail();
int Menu();
//defining New Customer's details
struct NewCustomer
{
char Name[20];
char Surname[20];
char Birthday[10];
char PhoneNum [15];
char Email[20];
};
NewCustomer entries [10000];
int count;
};
void DataCustomer::AddCustomer()
{
cout<<"Enter a Name: ";
ofstream a_file ("database.txt", ios::app);
cin >> entries[count].Name;
a_file << entries [count].Name<<"\n";
cin.clear();
cin.sync();
cout << "Enter a Surname: ";
cin >> entries[count].Surname;
a_file << entries[count].Surname << "\n";
cin.clear();
cin.sync();
cout << "Enter Date of Birth: ";
cin >> entries[count].Birthday;
a_file << entries[count].Birthday << "\n";
cin.clear();
cin.sync();
cout << "Enter Phone Number: ";
cin >> entries[count].PhoneNum;
a_file << entries[count].PhoneNum << "\n";
cin.clear();
cin.sync();
cout << "Enter Email: ";
cin >> entries[count].Email;
a_file << entries[count].Email << "\n";
a_file.close();
++count;
}
void DataCustomer::DisplayAll(int i)
{
system ("cls");
cout<<"Entire Customers' database:"<<endl;
ifstream a_file ( "database.txt" );
a_file>> entries[i].Name;
a_file>> entries[i].Surname;
a_file>> entries[i].Birthday;
a_file>> entries[i].PhoneNum;
a_file>> entries[i].Email;
cout << "Name : " << entries[i].Name << endl;
cout << "Surname: " << entries[i].Surname << endl;
cout << "Date of birth : " << entries[i].Birthday << endl;
cout << "Phone number : " << entries[i].PhoneNum << endl;
cout << "Email: " << entries[i].Email << endl;
cout << "Number of Entries : " << count << endl;
for(int i = 0;i < count;++i)
{cout << endl;
DisplayAll(i); }
}
DataCustomer db;
int main ()
{
db.DisplayAll(int i);
return 0;
}

How should we add function inside a structure?

#include <iostream>
using namespace std;
struct teacher
{
int id;
char name[50];
int salary;
void input(teacher a)
{
cout << "Enter Name : ";
cin >> a.name;
cout << "Enter ID : ";
cin >> a.id;
cout << "Enter Salary : ";
cin >> a.salary;
}
void output(teacher b)
{
cout << "Your Name Is : " << b.name << endl;
cout << "Your ID Is : " << b.id << endl;
cout << "Your Salary Is : " << b.salary;
}
};
int main()
{
teacher t;
t.input(t);
t.output(t);
return 0;
}
Is there any problem? The output is random numbers, don't know what is it.
I tried writing the output function separately, but still same results.
This seems like a weird design, why don't your class methods directly operate on this?
struct teacher
{
int id;
std::string name;
int salary;
void input()
{
cout << "Enter Name : ";
cin >> name;
cout << "Enter ID : ";
cin >> id;
cout << "Enter Salary : ";
cin >> salary;
}
void output() const
{
cout << "Your Name Is : " << name << endl;
cout << "Your ID Is : " << id << endl;
cout << "Your Salary Is : " << salary;
}
};
Then main would look like
int main()
{
teacher t;
t.input();
t.output();
return 0;
}
Also I'd prefer to use std::string instead of char[] when possible.
In input() you modify parameter a which goes out of scope when it reaches the end of the function.
Instead you should modify the class members variables themselves.
void input()
{
cout << "Enter Name : ";
cin >> name;
cout << "Enter ID : ";
cin >> id;
cout << "Enter Salary : ";
cin >> salary;
}

C++ Virtual Void

Okay, so I have a parent class called employee and 3 subclass called manager,researcher and engineer. I made a vector and want to list them. this is the how I process the making.
vector <Employee*,Manager*> EmployeeDB;
Employee *temp;
temp = new Manager(first, last, salary, meetings, vacations);
EmployeeDB.push_back(temp);
I have no problem in making the vector, my concern is listing the info. all 3 subclasses have firstname, lastname and salary but they're difference is that they have different data members which is unique, example the Manager has the int value vacation and the Engineer has the int value experience so on and so forth.
Employee.h:
#include <iostream>
#include <string>
using namespace std;
#ifndef EMPLOYEE_h
#define EMPLOYEE_h
class Employee
{
public:
Employee();
Employee(string firstname, string lastname, int salary);
string getFname();
string getLname();
int getSalary();
virtual void getInfo();
private:
string mFirstName;
string mLastName;
int mSalary;
};
#endif
Employee.cpp:
#include "Employee.h"
#include <iostream>
#include <string>
using namespace std;
Employee::Employee()
{
mFirstName = "";
mLastName = "";
mSalary = 0;
}
Employee::Employee(string firstname, string lastname, int salary)
{
mFirstName = firstname;
mLastName = lastname;
mSalary = salary;
}
string Employee::getFname()
{
return mFirstName;
}
string Employee::getLname()
{
return mLastName;
}
int Employee::getSalary()
{
return mSalary;
}
void Employee::getInfo()
{
cout << "Employee First Name: " << mFirstName << endl;
cout << "Employee Last Name: " << mLastName << endl;
cout << "Employee Salary: " << mSalary << endl;
}
Main:
#include <vector>
#include <iostream>
#include <string>
#include "Employee.h"
#include "Engineer.h"
#include "Manager.h"
#include "Researcher.h"
using namespace std;
vector <Employee*> EmployeeDB;
Employee *temp;
void add()
{
int emp, salary, vacations, meetings, exp, c;
string first, last, type, school, topic;
bool skills;
do
{
system("cls");
cout << "===========================================" << endl;
cout << " Add Employee " << endl;
cout << "===========================================" << endl;
cout << "[1] Manager." << endl;
cout << "[2] Engineer." << endl;
cout << "[3] Researcher." << endl;
cout << "Input choice: ";
cin >> emp;
system("cls");
} while (emp <= 0 || emp > 3);
cout << "===========================================" << endl;
cout << " Employee Info " << endl;
cout << "===========================================" << endl;
cout << "Employee First name: ";
cin >> first;
cout << "Employee Last name: ";
cin >> last;
cout << "Employee Salary: ";
cin >> salary;
switch (emp)
{
case 1:
cout << "Employee numbers of meetings: ";
cin >> meetings;
cout << "Employee numbers of vacations: ";
cin >> vacations;
temp = new Manager(first, last, salary, meetings,vacations);
EmployeeDB.push_back(temp);
delete temp;
break;
case 2:
cout << endl;
cout << "[1]YES [2]NO" << endl;
cout << "Employee C++ Skills: ";
cin >> c;
if (c == 1)
{
skills = true;
}
else
{
skills = false;
}
cout << "Employee Years of exp: ";
cin >> exp;
cout << "(e.g., Mechanical, Electric, Software.)" << endl;
cout << "Employee Engineer type: ";
cin >> type;
temp = new Engineer(first, last, salary, skills, exp, type);
EmployeeDB.push_back(temp);
delete temp;
break;
case 3:
cout << "Employee School where he/she got his/her PhD: ";
cin >> school;
cout << "Employee Thesis Topic: ";
cin >> topic;
temp = new Researcher(first, last, salary, school, topic);
EmployeeDB.push_back(temp);
delete temp;
break;
}
}
void del()
{
}
void view()
{
for (int x = 0; x < (EmployeeDB.size()); x++)
{
cout << EmployeeDB[x]->getInfo();
}
}
void startup()
{
cout << "===========================================" << endl;
cout << " Employee Database " << endl;
cout << "===========================================" << endl;
cout << "[1] Add Employee." << endl;
cout << "[2] Delete Employee." << endl;
cout << "[3] List Employees." << endl;
cout << "[4] Exit." << endl;
cout << "Please Enter Your Choice: ";
}
int main(int argc, char** argv)
{
bool flag = true;
int choice;
do {
do
{
system("cls");
system("pause>nul");
startup();
cin >> choice;
} while (choice < 0 || choice >4);
switch (choice)
{
case 1:
add();
break;
case 2:
del();
break;
case 3:
view();
break;
case 4:
flag = false;
system("EXIT");
break;
}
} while (flag == true);
return 0;
system("pause>nul");
}
I am getting error on the view() function.
It says no operator<< matches these operands
binary '<<': no operator found which takes a right hand operand of type void etc etc.
The problem is that the getInfo has return type void and you are trying to put that return value into cout.
It's important to understand that the code std::cout << val actually calls the function operator<<(ostream& out, const objectType& val) where objectType is the type of 'val'.
In your case the type is void, and there is simply no implementation of operator<< that takes void as a type. hence the error "no operator found which takes a right hand operand of type void...".
In order to fix your issue you have a few options:
Change view() to be
for (...)
{
EmployeeDB[x]->getInfo();
}
Change getInfo() to return a string the info as you'd like:
std::string getInfo()
{
std::string info;
info =...
return info;
}
Create an operator<< for Employee and change view to call it:
view()
{
for (...)
{
std::cout << EmployeeDB[x];
}
}

The search function does not work

Here is my code. It's homework but i have done it all. But the search function does not work. I know Im doing something wrong in it. The user has to enter a name to search and it should display the whole entry. There is an error at the void search function which says "error C2120: 'void' illegal with all types"
// Awholenew world.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<process.h>
#include<iomanip>
#include<stdio.h>
#include<string.h>
#include<fstream>
#include<sstream>
#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
struct main
{
char FName[20];
char Last[20];
char Address[30];
long Phone;
int ID;
long CNIC;
}obj;
class Main
{
public:
virtual void init()
{
cin.getline(obj.FName,20);
cout << "Enter Name: ";
cin.getline(obj.Last,20);
cout << "Enter Address: ";
cin.getline(obj.Address, 30);
cout << "Enter Phone: ";
cin>>obj.Phone;
}
void view()
{
cout << "Name: " << obj.Last<< endl;
cout << "Address: " << obj.Address << endl;
cout << "Phone: " << obj.Phone << endl;
cout << "CNIC: " << obj.CNIC << endl;
cout << "ID: " << obj.ID << endl;
}
virtual void search()
{
char choice4;
char Target[20];
int Found=0;
fstream fin;
if (fin.open("Main.txt", ios::in| ios::out) == NULL)
cout<<"File is empty" << endl;
else
cout<<"Enter Name: " << endl;
cin.getline(Target, 20);
while(!fin.eof() && Found ==0)
{
fin<< endl << obj.Last << endl <<obj.Address <<endl <<obj.Phone << endl << obj.CNIC << endl << obj.ID;
if (strcmp(Target, obj.Last) == 0)
Found =1;
}
if(Found)
{
Main::view();
}
else if (!Found)
printf("**There is no such Entry**\n");
fin.close();
}
void display()
{
char BUFFER[100];
ifstream fin("Main.txt");
while (!fin.eof())
{
fin.getline(BUFFER, 100);
cout << BUFFER << endl;
}
}
};
class Teacher : public Main
{
public:
void tinit()
{
ofstream fin("Main.txt", ios::app);
Main::init();
cout << "Enter CNIC of Teacher" << endl;
cin>>obj.CNIC;
fin<< endl << obj.Last << endl << obj.Address << endl << obj.Phone << endl << "Teacher CNIC: " << obj.CNIC << endl;
}
};
class Student : public Main
{
public:
void sinit()
{
ofstream fin("Main.txt", ios::app);
Main::init();
cout << "Enter ID of Student" << endl;
cin>>obj.Phone;
fin<< endl << obj.Last <<endl << obj.Address << endl << obj.Phone << endl << "Student ID" << obj.ID << endl;
}
};
class Employee : public Main
{
public:
void einit()
{
ofstream fin("Main.txt", ios::app);
Main::init();
cout << "Enter Employee CNIC" << endl;
cin>>obj.CNIC;
fin << endl << obj.Last <<endl << obj.Address << endl << obj.Phone << endl << "Employee CNIC: " << obj.CNIC << endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Main* myarr[100];
Teacher* tearr[100];
Student* starr[100];
Employee* emarr[100];
int var=0;
int choice;
char input;
start:
printf("===============MAIN MENU===============");
printf("\n[1]Insert\n[2]Display All\n[3]Search\n[4]Exit\n");
printf("=======================================");
printf("\n\nEnter Your Choice: ");
cin >> choice;
switch(choice)
{
case 1:
label:
cout<< "Enter Choice s/t/e" << endl;
cin >> input;
if (input == 't')
tearr[var]->tinit();
if (input == 's')
starr[var]->sinit();
if (input == 'e')
emarr[var]->einit();
cout << " Enter another (y/n)? ";
cin >> input;
if (input == 'y')
goto label;
else
goto start;
break;
case 2:
myarr[var]->display();
break;
case 3:
myarr[var]->search();
break;
case 4:
cout << "Are you sure? y/n" << endl;
char in;
cin>>in;
if (in=='y')
getch();
else goto start;
break;
default:
return 0;
break;
return 0;
}
}
One problem I can see is:
fstream fin;
if (fin.open("Main.txt", ios::in| ios::out) == NULL)
The function fstream::open is declared as:
void open ( const char * filename,
ios_base:openmode mode = ios_base::in | ios_base::out );
as you can see its return type is void, so you cannot use it in the if expression.
The most glaring thing I noticed is that it looks like the struct of type 'main' stored in the obj variable is outside of any particular class instance. This means that every single object of type Main, Employee, Student or Teacher is only writing to a single obj outside of its own scope. ALL Employees, Teachers, Students, 'Mains' will be sharing whatever FName, Last, Address values you wrote last.
What you probably want is for each instance of Main to have its own FName, Last, Address, etc...
class Main
{
struct main
{
char FName[20];
char Last[20];
char Address[30];
long Phone;
int ID;
long CNIC;
}obj;
public:
virtual void init()
{
... rest of code here
please reduce your post to the main problem. if you just list everything in a single "code" block. noone can understand what you do.
1: don't use "goto" !(!!!!!)
2: you sould realy use bool instead of int for flags
3: don't use main / Main for structs or class names. it's actually reserved for the mainmathod (on some systems) and it is confusing to have one class and one struct with the same name (ignoring the case)
4: you're accessing the function Main::view(); in your search method. but on which object ? normaly you should load the data to an object and accessing it via this->view();
5: the whole concept appear wired. why are you using a textfile and a polymorphic class hierarchy ? the textfile dumps the hierarchy. maybe you should reconsider your class concept.