The search function does not work - c++

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.

Related

c++ Problems with pushing structs onto a vector and then saving to an outputfile

I did away with the vector idea, and after a fair bit of faffing around managed to get the struct in and out of a file. I'm really enjoying the challenge of c++, so much to learn!!!
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
struct Account_query
{
public:
char name[50];
char number[50];
};
void AddRecord(Account_query* aq)
{
ofstream fout;
fout.open("Records.out", ios::app | ios::out | ios::binary);
cout << "Enter name: ";
cin >> aq->name;
cout << "Enter account number: ";
cin >> aq->number;
fout.write( reinterpret_cast<const char *>( &(*aq) ), sizeof(Account_query) );
fout.close();
}
void ShowRecord()
{
Account_query aq;
//std::memset(&aq, 0, sizeof(aq));
ifstream inf;
inf.open("Records.out", ios::binary);
if(!inf)
{
cout << "Problem opening"<<endl;
}
cout <<"####Data Out###"<<endl;
while(!inf.eof())
{
inf.read( reinterpret_cast<char *>(&aq.name), sizeof(Account_query::name));
inf.read( reinterpret_cast<char *>(&aq.number), sizeof(Account_query::number));
cout << "Name is: " << aq.name << "Account is: " << aq.number <<endl;
}
}
int main(int argc, const char * argv[]) {
vector<Account_query> list;
cout << "Welcome to Jizz Bank\n";
cout << "Enter one of the following options then press enter\n";
cout << "-----------------------------------\n";
cout << "1) Add Record \n";
cout << "2) Show Records \n";
cout << "3) Search Record \n";
cout << "4) Edit Record \n";
cout << "5) Delete Record \n";
cout << "-----------------------------------\n";
cout << "Enter your choice: ";
int x;
cin >>x;
Account_query a;
Account_query *p = &a;
switch(x)
{
case 1:{
AddRecord(p);//got the data for object now
break;
}
case 2:{
ShowRecord();
break;
}
default:{
exit(0);
}
}
return 0;
}
Previous entry below...
I'm trying to write a console program to learn c++.
In case 1 of the switch I'm dynamically creating a struct and then sending it to a function along with a reference to a vector.
The idea is to input some simple data to populate the struct, then to push this onto a vector and then write this to a file (binary).
The problem seems to be:
fout.write(static_cast<char*> (*it), sizeof(Account_query));
I get, Cannot cast from type 'Account_query' to pointer type 'char *' in Xcode.
I've tried reinterpret_cast amongst other things but that doesn't work either.
Would really appreciate any help,
LD.
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
struct Account_query
{
public:
char name[50];
char number[50];
};
void AddRecord(Account_query* aq, vector<Account_query>& list)
{
ofstream fout;
fout.open("Records.bank", ios::binary | ios::out);
cout << "Enter name: ";
cin >> aq->name;
cout << "Enter account number: ";
cin >> aq->number;
list.push_back(*aq);
for (vector<Account_query>::iterator it=list.begin(); it != list.end(); ++it)
{
fout.write(static_cast<char*> (*it), sizeof(Account_query));
}
fout.close();
}
void ShowRecord()
{
//TODO
}
int main(int argc, const char * argv[]) {
vector<Account_query> list;
cout << "Welcome to Jizz Bank\n";
cout << "Enter one of the following options then press enter\n";
cout << "-----------------------------------\n";
cout << "1) Add Record \n";
cout << "2) Show Records \n";
cout << "3) Search Record \n";
cout << "4) Edit Record \n";
cout << "5) Delete Record \n";
cout << "-----------------------------------\n";
cout << "Enter your choice: ";
int x;
cin >>x;
switch(x)
{
case 1:{
Account_query* a = new Account_query;
AddRecord(a, list);//got the data for object now
break;
}
case 2:{
cout<<"do nowt yet"<<endl;
break;
}
default:{
exit(0);
}
}
return 0;
}
Don't make life difficult for yourself. Start by using std::string, and then just use the operator<< to put the strings in the file (and read from it). e.g.
#include <string>
#include <iostream>
#include <fstream>
struct AccountQuery
{
std::string name;
std::string number;
};
AccountQuery AddRecord()
{
AccountQuery aq;
std::cout << "Enter name: ";
std::cin >> aq.name;
std::cout << "Enter account number: ";
std::cin >> aq.number;
{
std::ofstream fout("Records.out", std::ios::app | std::ios::binary);
fout << aq.name << " " << aq.number << " "; // spaces for simple separation.
}
return aq;
}
void ShowRecord()
{
AccountQuery aq;
std::ifstream fin("Records.out", std::ios::binary);
if(!fin)
{
std::cerr << "Problem opening file.\n";
return;
}
std::cout << "####Data Out###\n";
while(fin >> aq.name && fin >> aq.number) {
std::cout << "Name is: " << aq.name << ", Account is: " << aq.number << '\n';
}
}
int main() {
std::cout
<< "Welcome to Jizz Bank\n"
<< "Enter one of the following options then press enter\n"
<< "-----------------------------------\n"
<< "1) Add Record\n"
<< "2) Show Records\n"
<< "3) Search Record\n"
<< "4) Edit Record\n"
<< "5) Delete Record\n"
<< "6) Exit\n"
<< "-----------------------------------\n";
bool loop = true;
while(loop) {
std::cout << "Enter your choice: ";
int choice;
std::cin >> choice;
switch(choice)
{
case 1: {
AddRecord();//return value unused?
break;
}
case 2: {
ShowRecord();
break;
}
case 6: {
loop = false;
break;
}
default: {
// nothing, could be omitted
break;
}
}
}
}

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];
}
}

Call void function in IF statement C++

listSelectedDVD() should display the detail when i enter the title. but in my code Im able to enter the title but didn't display details.unable to pass-in argument.
#include <iostream>
#include <string>
using namespace std;
struct myStock // declare myStock fields
{
string title;
double price;
int stockLevel;
bool award;
};//end of strcut myStock
myStock list[5];
void initialize();
void listSelectedDVD(string);
int main()
{
int choice;
string enterTitle;
cout << "****** MAIN MENU ******" << endl;
cout << "1. List deatils of selected title" << endl;
cout << "4. Exit" << endl;
cout << endl;
cout << "enter your choice: " << endl;
cin >> choice;
if (choice == 1)
{
cout << "Enter a Title: " << endl;
cin >> enterTitle;
listSelectedDVD(enterTitle);
}
else if (choice == 4)
{
return 0;
}
system("PAUSE");
}//end of main
Here is my void Function of void initialize() & void listSelectedDVD(string enterTitle) ;
void initialize()
{
list[0].title = "Ilo Ilo";
list[0].price = 35.55;
list[0].stockLevel = 15;
list[0].award = true;
list[1].title = "Money Just Enough";
list[1].price = 10.35;
list[1].stockLevel = 0;
list[1].award = false;
}
void listSelectedDVD(string enterTitle)
{
for(int i=0;i<5;i++)
{
if (list[i].title.compare(enterTitle) == 0) //list[i].title == enterTitle
{
cout << "Title : " << list[i].title << endl;
cout << "Price : " << list[i].price << endl;
cout << "Stock : " << list[i].stockLevel << endl;
cout << "Award : " << list[i].award << endl;
}
else {
out<<"Invalid Title"<<endl;
//call back the main menu function//
}
}
}
You should first call initialize() from main before calling listSelectedDVD().
int main()
{
initialize();
//rest of your code
}//end of main
The main problem is, when you take the user input on this line "cin >> enterTitle;", it gets the first word you typed separated by space. So when you type
Money Just Enough
then the value of enterTitle just becomes "Money".
This is the reason why your program is unable to find any match. ("Money" is not the same as "Money Just Enough")
One way to solve this is to change your code so that you can receive an entire line as a string input.

Program reading from variables stored in itself and not from binary file

I'm working on a program very important to my programming class, and there's something I can't quite figure out; When I try to read from a binary file I've created after opening the program, it fails even if the file's in the directory, and after I try to wipe the contents of the file, I can still 'read' them from the file even though said file is empty when I examine it in explorer. I've determined from this that even though I'm using BinaryFile.read, it's not truly reading from the file, and instead reading from variables stored in the program itself. How can I get my program to read from the actual file?
(please note that this is not yet a complete program, hence the commented sections and empty functions.)
(Also please note that, due to the nature of my class, I am only allowed to use what has been taught already (namely, anything in the fstream header and most things before which are necessary to make a basic program - he's letting me use things in stdio.h, as well.)
//
// main.cpp
// Binary Program
//
// Created by Henry Fowler on 11/19/14.
// Copyright (c) 2014 Bergen Community College. All rights reserved.
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cstdlib>
#include <math.h>
#include <stdio.h>
using namespace std;
struct Record
{
char Name[20];
char LastName[20];
double Pay;
int Clearance;
int ID;
};
void CreateFile(fstream&); //Working
void CheckExist(fstream&); //Working
void Populate(fstream&,Record[],int&,int&); //Working
void Display(fstream&,Record[],int&,int&); //Working
void Append(fstream&,Record[],int&,int&); //Working
void DeleteFromFile(fstream&,fstream&,Record[],int&,int&);
// void SearchInFile(fstream&,Record[],int&,int&);
// void ModifyRecord(fstream&,Record[],int&,int&);
//void SortFile();
void WipeFile(fstream&);
void DelFile(fstream&);
int main(int argc, const char * argv[])
{
Record EmpRecords[20];
char Binary[] = "BinaryFile.dat";
char Binary2[] = "BinaryFileTemp.dat";
int maxsize; //make sure to set i to max size so you can use it later for things like wiping the file or deleting specific records
fstream BinaryFile;
fstream BinaryFile2;
string InputStr;
// char Read;
//int Choice = 0;
int i = 0;
int choice = 0;
int switchchoice;
CreateFile(BinaryFile); //working
CheckExist(BinaryFile); //working
BinaryFile.close();
while(choice==0)
{
cout << "Options: " << endl;
cout << "End Program (0)" << endl;
cout << "Input new records to file (1)" << endl;
cout << "Display current contents of file (2)" << endl;
cout << "Append a record at the end of the file (3)" << endl;
cout << "Delete a record from the file (4)" << endl;
cout << "Search for a record in the file (5)" << endl;
cout << "Modify a certain record (6)" << endl;
cout << "Sort file (unimplemented)" << endl;
cout << "Wipe contents of file (8)" << endl;
cout << "Please choose an option: ";
cin >> switchchoice;
switch(switchchoice)
{
case 0:
{
cout << "Exiting.";
BinaryFile.close();
system("PAUSE");
return 0;
break;
}
case 1:
{
Populate(BinaryFile, EmpRecords,i,maxsize); //working
break;
}
case 2:
{
Display(BinaryFile, EmpRecords,i,maxsize); //working i think
break;
}
case 3:
{
Append(BinaryFile, EmpRecords,i,maxsize); //working
break;
}
case 4:
{
DeleteFromFile(BinaryFile,BinaryFile2,EmpRecords,i,maxsize); //!
break;
}
case 5:
{
// SearchInFile(BinaryFile, EmpRecords,i,maxsize); //!
break;
}
case 6:
{
// ModifyRecord(BinaryFile, EmpRecords,i,maxsize); //!
break;
}
case 7:
{
cout << "Error, file sorting is currently unimplemented. Please try again.";
break;
}
case 8:
{
WipeFile(BinaryFile);
break;
}
}
}
system("PAUSE");
return 0;
}
void CreateFile(fstream& BinaryFile)
{
BinaryFile.open("BinaryFile.dat", ios::out | ios::binary);
}
void CheckExist(fstream &BinaryFile)
{
if(BinaryFile.good())
{
cout << endl << "File does exist" << endl;
}
else
{
cout << "file named can not be found \n";
system("PAUSE");
}
}
void Populate(fstream &BinaryFile,Record EmpRecords[],int &i, int &maxsize)
{
BinaryFile.open("BinaryFile.dat", ios::out | ios::binary);
int choice = 0;
while(choice==0)
{
cout << "Please input employee first name: ";
cin >> EmpRecords[i].Name;
cout << "Please input employee last name: ";
cin >> EmpRecords[i].LastName;
cout << "Please input Employee Pay: ";
cin >> EmpRecords[i].Pay;
cout << "Please input Employee Clearance (1-10): ";
cin >> EmpRecords[i].Clearance;
cout << "Please input Employee ID (6 numbers, i.e. 122934): ";
cin >> EmpRecords[i].ID;
cout << "Input another employee's information? (0) = yes, (1) = no: ";
cin >> choice;
BinaryFile.write((char *) (&EmpRecords[i]),sizeof(EmpRecords[i]));
i = i+1;
}
maxsize = i;
cout << "i is " << i << endl;
cout << "maxsize is " << maxsize << endl;
BinaryFile.close();
}
void Display(fstream &BinaryFile,Record EmpRecords[],int &i,int &maxsize)
{
BinaryFile.open("BinaryFile.dat", ios::in | ios::binary | ios::app);
int i2 = maxsize;
i = 0;
while(i2>0)
{
BinaryFile.read((char *) (&EmpRecords[i]),sizeof(EmpRecords[i]));
cout << i << endl;
cout << EmpRecords[i].Name << " " << EmpRecords[i].LastName << endl;
cout << "Pay: $" << EmpRecords[i].Pay << endl;
cout << "Clearance: " << EmpRecords[i].Clearance << endl;
cout << "Employee ID: " << EmpRecords[i].ID << endl;
BinaryFile.read((char *) (&EmpRecords[i]),sizeof(EmpRecords[i]));
cout << endl;
i2 = i2-1;
i = i+1;
}
BinaryFile.close();
}
void Append(fstream &BinaryFile,Record EmpRecords[],int &i,int &maxsize)
{
BinaryFile.open("BinaryFile.dat", ios::out|ios::binary|ios::ate|ios::app);
cout << "Please input employee first name: ";
cin >> EmpRecords[maxsize].Name;
cout << "Please input employee last name: ";
cin >> EmpRecords[maxsize].LastName;
cout << "Please input Employee Pay: ";
cin >> EmpRecords[maxsize].Pay;
cout << "Please input Employee Clearance (1-10): ";
cin >> EmpRecords[maxsize].Clearance;
cout << "Please input Employee ID (6 numbers, i.e. 122934): ";
cin >> EmpRecords[maxsize].ID;
cout << "Input another employee's information? (0) = yes, (1) = no: ";
BinaryFile.write((char *) (&EmpRecords[i]),sizeof(EmpRecords[i]));
maxsize = maxsize+1;
cout << "maxsize is " << maxsize << endl;
BinaryFile.close();
}
void DeleteFromFile(fstream &BinaryFile,fstream &BinaryFile2, Record EmpRecords[],int &i,int &maxsize)
{
BinaryFile.open("BinaryFile.dat", ios::out|ios::binary|ios::app);
BinaryFile2.open("BinaryFileTemp.dat", ios::out|ios::binary|ios::app);
int Choice;
cout << "Would you like to delete a file by name or by employee number?" << endl;
cout << "Name (1)" << endl;
cout << "Number (2)" << endl;
cout << "Choice: ";
cin >> Choice;
int i2 = maxsize;
if(Choice==1)
{
cout << "Please input employee first name: ";
// cin >> firstname;
cout << "Please input employee last name: ";
// cin >> lastname;
cout << "Searching...";
int i2 = maxsize;
i = 0;
while(i2>0)
{
BinaryFile.read((char *) (&EmpRecords[i]),sizeof(EmpRecords[i]));
cout << i << endl;
BinaryFile.read((char *) (&EmpRecords[i]),sizeof(EmpRecords[i]));
// if(EmpRecords[i].Name == firstname)
// {
// cout << "Found first name." << endl;
// if (EmpRecords[i].LastName == lastname)
// {
// cout << "Found last name." << endl;
/// }
// }
// else
// {
// cout << "Could not find name.";
// // BinaryFile2.write((char *) (&EmpRecords[i]),sizeof(EmpRecords[i]));
// }
cout << endl;
i2 = i2-1;
i = i+1;
}
}
BinaryFile.close();
if( remove( "BinaryFile.dat" ) != 0 )
cout << endl << "Error deleting file" << endl;
else
{
cout << "File successfully deleted" << endl << endl;
}
int result;
char oldname[]="BinaryFileTemp.dat";
char newname[]="BinaryFile.dat";
result = rename(oldname,newname);
if(result == 0)
cout << "DEBUG: Success" << endl;
else
cout << "DEBUG: Failure" << endl;
}
void WipeFile(fstream &BinaryFile)
{
int sure;
cout << "There is no undoing this action." << endl;
cout << "Continue (1)" << endl;
cout << "Cancel (2)" << endl;
cout << "Wipe file? ";
cin >> sure;
if(sure == 1)
{
cout << "Wiping file.";
BinaryFile.open("BinaryFile.dat", ios::out | ios::binary | ios::trunc);
BinaryFile.close();
}
else
{
cout << "Canceling.";
}
}
void DelFile(fstream &BinaryFile)
{
BinaryFile.close();
if( remove( "BinaryFile.dat" ) != 0 )
cout << endl << "Error deleting file" << endl;
else
{
cout << "File successfully deleted" << endl << endl;
}
}
Here the problem seems to be, even though you are wiping the file contents, you are not clearing the data you had stored in Record EmpRecords[20]; or the int maxsize value.
Few things you can do inside void WipeFile(fstream &BinaryFile) function: To keep it simple, we'll just reset maxsize to 0:
Pass the maxsize variable as reference to WipeFile(), the same way you are passing for Populate()
Update maxsize = 0, to indicate all the records are removed, when you delete the file contents.
It is better to memset the contents of EmpRecords as well similarly.
For now, I just modified your code to reset maxsize to 0 in WipeFile() and it worked.
void WipeFile(fstream &BinaryFile, int &maxsize)
{
int sure;
cout << "There is no undoing this action." << endl;
cout << "Continue (1)" << endl;
cout << "Cancel (2)" << endl;
cout << "Wipe file? ";
cin >> sure;
if(sure == 1)
{
cout << "Wiping file.";
BinaryFile.open("BinaryFile.dat", ios::out | ios::binary | ios::trunc);
BinaryFile.close();
maxsize = 0;
}
else
{
cout << "Cancelling.";
}
}

Address Book using Inheritance and Operator Overloading or Exception handling

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.