vector.erase - it deletes my last element always - c++

First time here, an amateur programmer, I have quite a bit of issue. I want to make a virtual model shop. I can add new items, check the inventory, all in a vector but when I want to delete a specific item (by producer&name&scale) it always deletes the last element.
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
class model
{
private:
int price;
string scale, name, producer;
public:
vector<model> vectorr;
model();
virtual ~model();
int getprice();
string getscale();
string getname();
string getproducer();
void setprice(int);
void setscale(string);
void setname(string);
void setproducer(string);
friend ostream &operator>>(ostream &stream, model &mt);
model &operator=(model &mt);
};
That's the header.
#include <iostream>
#include "header1.h"
#include <string>
#include <conio.h>
#include <vector>
using namespace std;
int main()
{
vector<machete> vectorr;
machete c;
machete t;
cout << "Welcome to the shop , what do you want to do?" << endl;
cout << "Chose your destiny : 1. Add 2.Get 3.Remove 4.Sort 0.Quit" << endl;
int menu, temp2;
string temp;
cin >> menu;
while (menu != 0) {
switch (menu) {
case 0 : cout << "Bye bye";
_getch();
exit(1);
break;
case 1 : cout << "Enter a producer" << endl;
cin >> temp;
c.setproducer(temp);
cout << "Enter a name" << endl;
cin >> temp;
c.setname(temp);
cout << "Enter a scale" << endl;
cin >> temp;
c.setscale(temp);
cout << "Enter a price" << endl;
cin >> temp2;
c.setprice(temp2);
vectorr.push_back(c);
cout << "You have succesfully added a model !" << endl;
break;
case 2 : cout << "Producer | Name | Scale | Price" << endl;
for (std::vector<model>::iterator it = vectorr.begin(); it != vectorr.end(); ++it) {
cout >> *it;
}
cout << endl;
break;
case 3 : cout << "What do you want to remove?" << endl;
cout << "Enter the producer" << endl;
string producer;
cin >> producer;
cout << "Enter the name" << endl;
string name;
cin >> name;
cout << "Enter the scale" << endl;
string scale;
cin >> scale;
for (unsigned i = 0; i < vectorr.size(); ++i) {
t.setname(vectorr[i].getnume());
t.setproducer(vectorr[i].getproducator());
t.setscale(vectorr[i].getscara());
if (t.getname() == name && t.getproducer() == producer && t.getscle() == scale) {
vectorr.erase(vectorr.begin() + i);
cout << "You have succesfully erased the " << name << " model" << endl;
break;
}
}
break;
}
cout << "Chose your destiny : 1. Add 2.Get 3.Remove 4.Sort 0.Quit" << endl;
cin >> menu;
}
return 0;
}
That's the main. case 3 is the problem deleting thingamajack. It always deletes the last element in my vector. The if(name=name and so on) works properly, tested it three times to be sure that wasn't the problem. It appears whatever I write vectorr.erase just won't work the way I want it to.
Sorry for the messy code, I might have done something wrong before the case 3, ignore case 4 the sort, not implemented yet, any help is appreciated, thanks!

In case 2, you've written
std::vector<model>::iterator it = vectorr.begin()
whereas you defined
vector<machete> vectorr;
I think you've confused between machete and model.

Related

Trying to incorporate void functions into switch statements

I'm a novice coding student and trying to create a menu using structs, functions, and switch statements to make a mini database for a class assignment. I'm trying to implant the functions into the switch statements.
I'm getting errors on lines 87 and 137 and I'm not sure where I'm going wrong. Any help, explanation, or correction is much appreciated.
#include <iostream>
#include <string>
#include <iomanip>
#include <sstream>
using namespace std;
// Jaret Clark
// Week 3 Interactive Assignment
// INT 499
// Prof. Joseph Issa
// 03/31/2022
struct EZTechMovie {
string name;
string *cast[10];
string rating;
};
void displaymovie(EZTechMovie movie, int cast_num) {
int i;
cout << endl;
cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << endl;
cout << endl;
cout << "Your entry:\n";
//Movies
cout << endl;
cout << "Movie TITLE: " << movie.name;
cout << endl;
//Movie rating
cout << "Movie Rating: " << movie.rating;
cout << endl;
//Cast name
cout << "Main Cast Members: \n";
//loop for cast members ~ stores in array
for (int i = 0; i < cast_num; ++i) {
cout << movie.cast[i];
cout << endl;
}
}
void mainmenu() {
string movie_input;
int m;
cout << endl;
cout << "Would you like to store movies into database? (yes or no) ";
getline(cin, movie_input);
cout << endl;
if (movie_input == "yes") {
string cont;
string cast_name;
int x, m, n, i, cast_num;
EZTechMovie moviedb[100];
cout << endl;
cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << endl;
cout << endl;
for (n = 0; n < 100; n++) {
cout << "Movie Title: ";
getline(cin, moviedb[n].name);
cout << endl;
cout << "Movie rating: ";
getline(cin, moviedb[n].rating);
cout << endl;
cout << "How many cast do you want to enter? ";
cin >> cast_num;
cout << endl;
cin.ignore();
for (i = 0; i < cast_num; i++) {
cout << "Cast name: First and Last name: ";
getline(cin, moviedb[n].cast[i]);
cout << endl;
}
cout << endl;
displaymovie(moviedb[n], cast_num);
cout << endl;
cout << "Add more movies? (yes or no) ";
getline(cin, cont);
if (cont == "no") {
break;
}
cout << endl;
cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << endl;
cout << endl;
}
}
else if (movie_input == "no") {
return;
}
else {
cout << "INVALID Input";
mainmenu();
}
}
// menu
void movieMenu() {
int choice;
EZTechMovie movie;
do {
cout << "***********************Welcome to EZTechMovie Movie Entry Menu***********************" << endl;
cout << "Press 1 to Enter Movie Info - Name, Cast Members, and Rating.\n";
cout << "Press 2 to Retrieve movie info recently entered.\n";
cout << "Press 3 To Quit program.\n";
// evaluate menu options in switch case
switch (choice) {
case 1:
mainmenu();
break;
case 2:
displaymovie(EZTechMovie movie, int cast_num);
break;
case 3:
cout << "Thank you and Goodbye!";
break;
default:
cout: "Invalid Selection. Try again!\n";
}
//get menu selection
cin >> choice;
} while (choice != 3);
}
int main() {
movieMenu();
}
Regarding the error on line 87 (getline(cin, moviedb[n].cast[i]);) :
moviedb[n].cast[i] is a std::string*, not std::string like you might have meant.
A quick compilation fix would be to use:
getline(cin, *(moviedb[n].cast[i]));
i.e. dereference the pointer.
However - this code raises other design/programming issues:
Why do you use std::string* and not std::string in the first place.
Why do you use C style array instead of std::vector (or std::array if you can commit to the size). This is relevant for both: string *cast[10]; and EZTechMovie moviedb[100];

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

Unable to solve the probelm

In the adding user section in the code below, I am unable to type any characters for the "Add another person?(y/n): " question. it just jumps back to entering age. How do I fix this?
I've tried to change ans into a string, implement a while loop to force the question to show up, and many other things. It just seems that nothing works and I've been trying it for the good part of two hours
#include <iostream>
#include <string>
#include <Windows.h>
using namespace std;
int main()
{
char ans;
int people;
int option;
int count = 0;
struct data
{
string name;
int age;
char gender;
string comments;
}person[100];
// homescreen
homescreen:
cout << "Welcome to the Data Base!" << endl;
cout << endl;
// displaying all people
for (int list = 0; list < count; list++)
{
cout << list << ".) " << person[list].name << endl;
}
cout << endl;
cout << "[1] View Person" << endl;
cout << "[2] Add Person" << endl;
cout << "[3] Edit Person" << endl;
cout << "[4] Delete Person" << endl;
cout << "[5] Exit" << endl;
cout << "Choose Option: "; cin >> option;
// using options
while (option != 5)
{
if (option == 1)
{
view:
for (int list2 = 0; list2 < count; list2++)
{
cout << list2 << ".) " << person[list2].name << endl;
}
cout << endl;
cout << "Enter number of person you want: "; cin >> people;
system("cls");
cout << "Name: " << person[count].name << endl;
cout << "Age: " << person[count].age << endl;
cout << "Gender: " << person[count].gender << endl;
cout << "Comments: " << person[count].comments << endl << endl;
cout << "View another person?(y/n): "; cin >> ans;
if (ans == 'y')
{
system("cls"); goto view;
}
else if (ans == 'n')
{
system("cls"); goto homescreen;
}
}
if (option == 2)
{
add:
system("cls");
cout << "Name: "; cin >> person[count].name;
system("cls");
cout << "Age: "; cin >> person[count].age;
system("cls");
cout << "Gender(M/F/H): "; cin >> person[count].gender;
system("cls");
cout << "Comments: "; cin >> person[count].comments;
count++;
system("cls");
cout << "Add another person?(y/n): "; cin >> ans;
if (ans == 'y')
{
system("cls");
goto add;
}
else if (ans == 'n')
{
system("cls");
goto homescreen;
}
}
}
}
If you anybody can help me I'd be grateful
The goto statements in your code makes the program really good
spaghetti
structure and that is not
good.
Therefore, think instead of goto other options, such as infinite
while loop which will break once the user enters the n or moving
the code to the function.
Secondly what if you have not entered any persons and choosing the
option 1. You still output the attributes of the person as
count is initialized zero at least. Remember the attributes are
not initialized at this point. Accessing the uninitialized
variables will invoke undefined
behavior. Therefore,
provide a check (something like if(count > 0) )before you execute the code in option 1.
In addition to that, remember that
std::endl flushes the output buffer, and '\n' doesn't. Therefore, most of
the cases you might wanna use just
\n.
Last but not the least, use std::vector instead of the using C style arrays with some predefined size. What if the user has more than 100 inputs? The solution in C++ is std::vector, which can expand dynamically as its storage is handled automatically.
Following is a possible solution to your program, in which the comments will guide you through to the things that I mentioned above.
#include <iostream>
#include <string>
#include <vector>
#include <windows.h>
struct Data
{
std::string name;
int age;
char gender;
std::string comments;
Data(const std::string& n, int a, char g, const std::string& c) // provide a Constructor
:name(n), age(a), gender(g), comments(c)
{}
};
void debugMsg(const std::string& msg)
{
system("cls");
std::cout << "\n\n\t\t" << msg << "\n\n";
Sleep(3000);
}
int main()
{
std::vector<Data> person; // use std::vector to store the datas
while (true) // loop: 1
{
system("cls");
std::cout << "Welcome to the Data Base! \n\n";
std::cout << "[1] View Person\n";
std::cout << "[2] Add Person\n";
std::cout << "[3] Edit Person\n";
std::cout << "[4] Delete Person\n";
std::cout << "[5] Exit\n";
std::cout << "Choose Option: ";
int option; std::cin >> option;
switch (option) // use switch to validate the options
{
case 1:
{
while (true) // loop - 2 -> case 1
{
// if no data available to show -> just break the loop 2 and return to the outer loop(i.e, loop 1)
if (person.empty()) { debugMsg("No person available to show ....going to main manu...."); break; }
// otherwise: displaying all people
for (std::size_t index = 0; index < person.size(); ++index)
std::cout << index << ".) " << person[index].name << "\n";
std::cout << "\nEnter number of person you want: ";
std::size_t index; std::cin >> index;
// if the index is not valid -> just break the loop 2 and return to the outer loop(i.e, loop 1)
if (index < 0 || index >= person.size()) { debugMsg("Sorry, wrong index!... returning to the main menu......"); break; }
system("cls");
std::cout << "Name: " << person[index].name << std::endl;
std::cout << "Age: " << person[index].age << std::endl;
std::cout << "Gender: " << person[index].gender << std::endl;
std::cout << "Comments: " << person[index].comments << std::endl << std::endl;
std::cout << "View another person?(y/n): ";
char ans; std::cin >> ans;
if (ans == 'y') { system("cls"); continue; } // just continue looping
else if (ans == 'n') { break; } // this will break the loop 2 and return to the outer loop(i.e, loop 1)
else { debugMsg("Sorry, wrong option!... returning to the main menu......"); break; }
}
} break;
case 2:
{
while (true) // loop - 3 -> case 2
{
system("cls");
std::string name, comments; int age; char gender;
std::cout << "Name: "; std::cin >> name;
std::cout << "Age: "; std::cin >> age;
std::cout << "Gender(M/F/H): "; std::cin >> gender;
std::cout << "Comments: "; std::cin >> comments;
// simply construct the Data in person vector in place
person.emplace_back(name, age, gender, comments);
std::cout << "\n\nAdd another person?(y/n): ";
char ans; std::cin >> ans;
if (ans == 'y') { system("cls"); continue; }
else if (ans == 'n') { system("cls"); break; } // same as case 1
else { debugMsg("Sorry, wrong option!... returning to the main menu......"); break; }
}
} break;
case 3: { /*code*/ debugMsg("Sorry, Not implemented!... returning to the main menu......"); } break;
case 4: { /*code*/ debugMsg("Sorry, Not implemented!... returning to the main menu......"); } break;
case 5: return 0; // if its 5, just retun the main
default: break;
}
}
return 0;
}
As mentioned above, using "goto" is a bad style, so i would suggest structure your program a little. Below is my version.
Naturally, I did not add any checks and controls, the author will be able to do this on his own. But main logics should work. And, of course, it is better to use vector instead of static array.
#include <iostream>
#include <string>
#include <Windows.h>
using namespace std;
enum options { OPT_VIEW = 1, OPT_ADD = 2, OPT_EDIT = 3, OPT_DELETE = 4, OPT_EXIT = 5 };
struct data
{
string name;
int age;
char gender;
string comments;
};
class App
{
private:
data person[100];
int count = 0;
public:
App();
void Run();
int HomeScreen();
void View();
void Add();
};
App::App() : count(0)
{}
void App::Run()
{
int option = HomeScreen();
while(option != OPT_EXIT)
{
switch(option)
{
case OPT_VIEW:
View();
break;
case OPT_ADD:
Add();
break;
}
option = HomeScreen();
}
}
int App::HomeScreen()
{
int option = 0;
cout << "Welcome to the Data Base!" << endl;
cout << endl;
// displaying all people
for(int list = 0; list < count; list++)
{
cout << list << ".) " << person[list].name << endl;
}
cout << endl;
cout << "[1] View Person" << endl;
cout << "[2] Add Person" << endl;
cout << "[3] Edit Person" << endl;
cout << "[4] Delete Person" << endl;
cout << "[5] Exit" << endl;
cout << "Choose Option: "; cin >> option;
return option;
}
void App::View()
{
char ans = 0;
do
{
int people = 0;
for(int list2 = 0; list2 < count; list2++)
{
cout << list2 << ".) " << person[list2].name << endl;
}
cout << endl;
cout << "Enter number of person you want: "; cin >> people;
system("cls");
cout << "Name: " << person[people].name << endl;
cout << "Age: " << person[people].age << endl;
cout << "Gender: " << person[people].gender << endl;
cout << "Comments: " << person[people].comments << endl << endl;
cout << "View another person?(y/n): "; cin >> ans;
}
while(ans == 'y');
system("cls");
}
void App::Add()
{
char ans = 0;
do
{
system("cls");
cout << "Name: "; cin >> person[count].name;
system("cls");
cout << "Age: "; cin >> person[count].age;
system("cls");
cout << "Gender(M/F/H): "; cin >> person[count].gender;
system("cls");
cout << "Comments: "; cin >> person[count].comments;
count++;
system("cls");
cout << "Add another person?(y/n): "; cin >> ans;
}
while(ans == 'y');
system("cls");
}
int main()
{
App program;
program.Run();
}

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

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.