Building arrays in a class and unhandled exceptions - c++

I am very new to programming and I was trying to create a phone book application involve arrays. I want to essentially take a large number of contact's info and have the person be able to search for them.
Every time I try to compile the code, it works, and then when I press 1 to enter a contact and I enter the first name, I get this "Unhandled exception at 0x000f2ceb in assignment7.23.exe: 0xC0000005: Access violation reading location 0x99d0627c."
I'm not sure what this means or what is wrong with my code.
Thank you in advance.
#include <iostream>
#include <string>
using namespace std;
class AddressBook {
public:
string myContactsFirstName[100];
string myContactsLastName[100];
string myContactsEmailAddress[100];
string myContactsPhone[100];
int index;
AddressBook() {
int index = 0;
for (int i = 0; i < 100; i++) {
myContactsFirstName[i] = "";
myContactsLastName[i] = "";
myContactsEmailAddress[i] = "";
myContactsPhone[i] = "";
}
}
void addContact() {
cout << "Enter the first name of the contact: " << endl;
string firstname;
cin >> firstname;
myContactsFirstName[index] = firstname;
cout << "Last Name:" << endl;
string lastname;
cin >> lastname;
myContactsLastName[index] = lastname;
cout << "Phone Number: " << endl;
string phone;
cin >> phone;
myContactsPhone[index] = phone;
cout << "Email Address: " << endl;
string address;
cin >> address;
myContactsEmailAddress[index] = address;
system("pause");
index++;
}
void deleteLastContact(){
myContactsFirstName[index] = "";
myContactsLastName[index] = "";
myContactsPhone[index] = "";
myContactsEmailAddress[index] = "";
index--;
cout << "Contact deleted." << endl;
}
};
int main() {
AddressBook myPeople;
string target;
while(1){
cout << "Enter 1 to add a contact." << endl;
cout << "Enter 2 to search contacts." << endl;
cout << "Enter 3 to delete a contact." << endl;
cout << "Enter anything else to leave the program" << endl;
int choice;
cin >> choice;
switch (choice) {
case 1: myPeople.addContact();
break;
case 2: {
cout << "Enter the info to search for your contact:" << endl;
cin >> target;
for (int i = 0; i < myPeople.index; i++) {
if (myPeople.myContactsFirstName[i].compare(target) == 0 )
cout << "We have a match" << endl;
}
break;
}
case 3: {
myPeople.deleteLastContact();
break;
}
default: exit(0);
}
}
system("pause");
return 0;
}

Index is uninitialized:
AddressBook() {
int index = 0; //created a new index variable, fix this by deleting "int"
^^^
for (int i = 0; i < 100; i++) {
myContactsFirstName[i] = "";
myContactsLastName[i] = "";
myContactsEmailAddress[i] = "";
myContactsPhone[i] = "";
}
}

Related

Writing from file to class

Making a project I have to write patient database and I have a problem. Looking through guids in iтternet I dont understand how to read from file to class and how to write class into file(I realized it using common input, it is better to rewrite it).
And I dont understand how to make base constructor for char, like with int
point()
{
x=y=z=0;
}
need like
Patient()
{
name="Mike";
surename="Smith";
adress="New York";
ilness="Cold"
card_number=1;
}
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int add();
int read();
string path = "base.txt";
class Patient
{
private:
char *name;
char *surename;
char *adress;
char *ilness;
int *card_number;
public:
void set()
{
cout << "Enter name:";
cin >> name;
cout << "Enter surename:";
cin >> surename;
cout << "Enter adress:";
cin >> adress;
cout << "Enter diagnosis:";
cin >> ilness;
cout << "Enter card number:";
cin >> *card_number;
}
void show()
{
cout << "Name:" << name << endl;
cout << "Surename:" << surename << endl;
cout << "Adress:" << adress << endl;
cout << "Cardnumber:" << card_number << endl;
cout << "Diagnosis:" << ilness << endl;
}
void print()
{
cout << name << surename << adress << ilness << card_number << endl;
}
Patient()
{
}
Patient(const char* s)
{
int length = 0;
while (s[length++] != ' ')
;
name = new char[length];
for (int i = 0; i < length; i++)
name[i] = s[i];
length = 0;
while (s[length++] != ' ')
;
surename = new char[length];
for (int i = 0; i < length; i++)
surename[i] = s[i];
length = 0;
while (s[length++] != ' ')
;
adress = new char[length];
for (int i = 0; i < length; i++)
adress[i] = s[i];
length = 0;
while (s[length++] != ' ')
;
ilness = new char[length];
for (int i = 0; i < length; i++)
ilness[i] = s[i];
length = 0;
while (s[length++] != '\n')
;
card_number = new int[length];
for (int i = 0; i < length; i++)
card_number[i] = s[i];
}
};
int main()
{
char a;
cout << "Choose the action:" << endl;
cout << "a. Add new patient" << endl;
cout << "b. Delete patient" << endl;
cout << "c. Find for card number" << endl;
cout << "d. Find for ilnesses" << endl;
cin >> a;
switch (a)
{
case 'a':
add();
break;
case 'b':
read();
break;
default:
cout << "error" << endl;
}
system("pause");
return 0;
}
int add()
{
fstream file;
file.open(path, fstream::out | fstream::in | ofstream::app);
if (!file.is_open())
{
cout << "Error" << endl;
}
else
{
string str;
cout << "Opend" << endl;
cout << "Enter name" << endl;
cin >> str;
file << str<<" ";
cout << "Enter surename" << endl;
cin >> str;
file << str << " ";
cout << "Enter adress" << endl;
cin >> str;
file << str << " ";
cout << "Enter ilness" << endl;
cin >> str;
file << str << " ";
cout << "Enter card number" << endl;
cin >> str;
file << str<<"\n";
cout << "Sucsesfully added\n";
}
file.close();
return 0;
}
int read()
{
fstream file;
file.open(path, fstream::out | fstream::in | ofstream::app);
if (!file.is_open())
{
cout << "Error" << endl;
}
else
{
cout << "Opend" << endl;
string str;
Patient first;
while (file.read((char*)&first,sizeof(Patient)))
{
first.print();
}
}
file.close();
return 0;
}
Database example
Mike Smith New_York Cold 1
Charles Williams London Flu 2
Henry Roberts York Coronovirus 3
Robert Garcia Sydney Cold 4
methods how to write from file to class and from class to file
If you want to serialise your data structures, it's best to use a library and data format, such as JSON.
Personally, I recommend nlohmann::json because of it's ease of use and flexibility.
Overloading the constructor and serialising data
Overloading your constructor is nothing other than overloading another method in C++.
If your class is Patient:
#include <string>
#include <nlohmann/json.hpp>
using nlohmann::json;
using std::string; // Don't use using namespace std;!
class Patient {
public:
Patient() = default;
explicit Patient(const string& name, const string& surname,
const string& addr, const string& illness):
m_name(name), m_surname(surname), m_address(addr), m_illness(illness) {}
explicit Patient(const json& data) { fromJson(data); }
virtual ~Patient() = default;
json toJson() const {
return {
{ "Name", m_name },
{ "Surname", m_surname },
{ "Address", m_address },
{ "Illness", m_illness }
};
}
void fromJson(const json& data) {
if (data.contains("Name") && data["Name"].is_string()) {
m_name = data["Name"].get<string>();
} // and so on
}
void dumpJson(const string& filePath) const {
ofstream out(path, std::ios::out);
// error checking
out << filePath;
}
private: // members
string m_name;
string m_surname;
string m_address;
string m_illness;
};
I haven't tested this code and won't guarantee it will work first try, but it should point you in the right direction. This code requires at least C++11.

Passing a struct array and updating array in C++

For one of my options, I had to add a row of data to my struct array, I was able to update the array but it does not update the actual array. So I am trying to update my struct array by passing it as a reference. I placed the '&' sign before the name of the variable, but all my indexes within the function errored.. I'm still a newbie to programing and I'm not "allowed " to use any vectors according to my Professor. . I looked online and placed the '&' on the function name as well as on the prototype. I also changed it from void to the "data type" to return the updated array, but no luck... I hope this comes out clear....
#include<iostream>
#include<iomanip>
#include<fstream>
using namespace std;
struct Data {
string first_name;
string last_name;
int employee_id;
string phone_number;
};
void readFile( ifstream& , string, Data [],int&);
void getEmployeeDetail(Data [], int&);
void getEmployeeLast(Data [], int&);
Data getAddEmployee(Data &, int&);
void getRemoveEmployee();
void getManagerOnly();
void getStaffOnly();
const int SIZE = 15;
Data employee[SIZE];
int main() {
ifstream inputFile;
ofstream outputFile;
int count = 0;
int selection;
const int EMPLOYEE_DETAIL = 1,
EMPLOYEE_LAST = 2,
ADD_EMPLOYEE = 3,
REMOVE_EMPLOYEE = 4,
MANAGER_ONLY = 5,
STAFF_ONLY = 6,
QUIT = 7;
readFile( inputFile ,"employeeData.txt", employee,count);
do {
cout << "\t Please select your option.\n"
<< "1. List all employee details\n"
<< "2. List employee by last name\n"
<< "3. Add a new employee\n"
<< "4. Remove an employee\n"
<< "5. Show all managers only\n"
<< "6. Show all staff only\n"
<< "7. Quit\n"
<< "Please enter your selection.\n" << endl;
cin >> selection;
while (selection < EMPLOYEE_DETAIL || selection > QUIT) {
cout << " Pleasse enter a valid selection.\n";
cin >> selection;
}
switch (selection) {
case EMPLOYEE_DETAIL:
getEmployeeDetail(employee,count);
break;
case EMPLOYEE_LAST:
getEmployeeLast(employee, count);
break;
case ADD_EMPLOYEE:
getAddEmployee(employee, count);
break;
case REMOVE_EMPLOYEE:
getRemoveEmployee();
break;
case MANAGER_ONLY:
getManagerOnly();
break;
case STAFF_ONLY:
getStaffOnly();
break;
case QUIT:
cout << "Program ending\n";
break;
}
} while (selection != QUIT);
system("pause");
return(0);
}
void readFile(ifstream& inputFile, string data, Data employee[],int &count) {
inputFile.open(data);
if (!inputFile) {
cout << " Error in opening file\n";
exit(1);
}
else {
while (!inputFile.eof()) {
inputFile >> employee[count].first_name;
inputFile >> employee[count].last_name >> employee[count].employee_id >> employee[count].phone_number;
count++;
}
inputFile.close();
}
return;
};
void readFile(ifstream& inputFile, string data, Data employee[],int &count) {
inputFile.open(data);
if (!inputFile) {
cout << " Error in opening file\n";
exit(1);
}
else {
while (!inputFile.eof()) {
inputFile >> employee[count].first_name;
inputFile >> employee[count].last_name >> employee[count].employee_id >> employee[count].phone_number;
count++;
}
inputFile.close();
}
return;
};
void getEmployeeDetail( Data employee[], int& count) {
cout << "Firt Name" << "\t" << "Last Name " << "\t" << "Employee ID " << "\t" << "Phone Number \n";
cout << "--------------------------------------------------------------------------\n";
for(int i =0; i < count; i++)
cout <<employee[i].first_name<<"\t\t"<<employee[i].last_name<<"\t\t"<<employee[i].employee_id<<"\t\t"<<employee[i].phone_number<< "\n ";
cout << endl;
}
void getEmployeeLast(Data employee[], int& count) {
string searchName;
cout << "Please enter the last name of the employee you want to search for.\n";
cin >> searchName;
/*
for (int i = 0; i < count; i++)
if (searchName ==employee[i].last_name) {
cout << employee[i].last_name;
}
*/
string matchString = searchName;
for (int i = 0; i < count; i++) {
if (employee[i].last_name.find(matchString, 0) != std::string::npos) {
cout << employee[i].last_name << endl;
}
else {
cout << "No employee was located with that name.\n";
exit(1);
}
}
}
Data getAddEmployee(Data &employee, int& count) {
string firstName, lastName, phoneNumber;
int employeeID, size;
for (int i = 0; i < count; i++)
cout << employee[i].first_name << "\t\t\t" << employee[i].last_name << "\t\t" << employee[i].employee_id << "\t\t" << employee[i].phone_number << "\n ";
cout << endl;
cout << count <<"\n";
size = count + 1;
cout << size << "\n";
cout << "Please enter the new employee First Name.\n";
cin >> firstName;
cout << "Please enter the new employee Last Name.\n";
cin >> lastName;
cout << "Please enter the new employee's ID.\n";
cin >> employeeID;
cout << "Please enter the new employee Phone Number.\n";
cin >> phoneNumber;
employee[10].first_name = firstName;
employee[10].last_name = lastName;
employee[10].employee_id = employeeID;
employee[10].phone_number = phoneNumber;
for (int i = 0; i < size; i++) {
cout << employee[i].first_name << "\t\t\t" << employee[i].last_name << "\t\t" << employee[i].employee_id << "\t\t" << employee[i].phone_number << "\n ";
cout << endl;
}
return employee;
}
First of all, your naming could be better. Like employeeList instead employee to specify its a list/array of employee, also addEmployee instead of getAddEmployee.
Second, instead of pasting whole code, it's better to paste the relevant block of code based on your question to make it clearer.
The solution is, your array is basically already on global scope, you don't need to pass it. Can just directly modify the array.
struct Data {
string first_name;
string last_name;
int employee_id;
string phone_number;
};
void addEmployee();
const int SIZE = 15;
Data employeeList[SIZE];
int current = 0;
int main(){
Data emp1 = {"John", "Doe", 100, "12345"};
employeeList[0] = emp1;
current++;
addEmployee();
for(int i=0; i<current; i++){
Data emp = employeeList[i];
cout<<i+1<<" "<<emp.first_name<<" "<<emp.phone_number<<endl;
}
}
void addEmployee(){
Data emp2 = {"Sam", "Smith", 200, "67890"};
employeeList[current] = emp2;
current++;
}
Can try it here: https://onlinegdb.com/drhzEOpis

String Type Vector C++

In the code I shared below, I want to output vector data type in the AddStoreCustomer() section. This is how the code works. But there is a bug in the code. If I enter a single word in the customer variable, the code works fine. But when I enter two words in this variable with a space between them,the code doesn't work.
#include <iostream>
#include <vector>
using namespace std;
class Store {
int StoreID;
string StoreName;
string StoreCity;
string StoreTown;
string StoreTel;
vector <string> StoreCustomer;
public:
Store(){}
Store(int sid, string sname, string scity, string stown, string stel, string scustomer) {
setStoreID(sid);
setStoreName(sname);
setStoreCity(scity);
setStoreTown(stown);
setStoreTel(stel);
setStoreCustomer(scustomer);
}
void setStoreID(int sid) {
StoreID = sid;
}
void setStoreName(string sname) {
StoreName = sname;
}
void setStoreCity(string scity) {
StoreCity = scity;
}
void setStoreTown(string stown) {
StoreTown = stown;
}
void setStoreTel(string stel) {
StoreTel = stel;
}
void setStoreCustomer(string scustomer) {
StoreCustomer.push_back(scustomer);
}
int getStoreID() {
return StoreID;
}
string getStoreName() {
return StoreName;
}
string getStoreCity() {
return StoreCity;
}
string getStoreTown() {
return StoreTown;
}
string getStoreTel() {
return StoreTel;
}
vector <string> getStoreCustomer() {
return StoreCustomer;
}
~Store(){}
};
Store s2[50];
void AddStore() {
int id, menu;
string name, city, town, tel;
for (int i = 0; i < 1; i++) {
cout << "Lutfen Magaza ID Numarasini Girin: ";
cin >> id;
s2[i].setStoreID(id);
cout << "Lutfen Magaza Adini Girin: ";
cin >> name;
s2[i].setStoreName(name);
cout << "Lutfen Magazanin Bulundugu Ili Girin: ";
cin >> city;
s2[i].setStoreCity(city);
cout << "Lutfen Magazanin Bulundugu Ilceyi Girin: ";
cin >> town;
s2[i].setStoreTown(town);
cout << "Lutfen Magazanin Telefon Numarasini Girin: ";
cin >> tel;
s2[i].setStoreTel(tel);
cout << "Magaza Eklendi" << endl;
cout << "\n\n";
}
cout << "Menuye Donmek icin 0 " << endl;
cin >> menu;
if (menu == 0) {
StoreMenu();
}
else {
cout << "Tanımlanamayan Giris!!!" << endl;
//Menu();
}
}
int Search2(const int& y) {
for (int j = 0; j < 100; j++) {
if (s2[j].getStoreID() == y)
return j;
}
return -1;
}
void AddStoreCustomer() {
int id, found, menu;
string customer;
cout << "Lutfen Musteri Eklemek Istediginiz Magazanin ID Numarasini Girin:";
cin >> id;
found = Search2(id);
if (found == -1)
{
cout << "Magaza Bulunamadi" << endl;
}
else {
cout << "Magaza Bulundu.\n" << "Lutfen Magaza Veri Tabanina Eklemek Istediginiz Musterinin Bilgilerini Girin: ";
cin >> customer;
s2[found].setStoreCustomer(customer);
cout << "Girilen Musteri Bilgisi Secilen Magazaya Eklendi";
cout << "Magaza ID: " << s2[found].getStoreID() << "\n Magaza Adi: " << s2[found].getStoreName() << "\n Magazanin Bulundugu Il: " << s2[found].getStoreCity() << "\n Magazanin Bulundugu Ilce:" << s2[found].getStoreTown() << "\n Magaza Iletisim Numarasi: " << s2[found].getStoreTel() << endl;
cout << "Musteriler: " << endl;
for (int i = 0; i < s2[found].getStoreCustomer().size(); i++)
{
cout << "\t\t" << s2[found].getStoreCustomer()[i] << endl;
}
}
cout << "Tekrar Giris Yapmak icin 1 Menuye Donmek icin 0 " << endl;
cin >> menu;
if (menu == 0) {
StoreMenu();
}
else if (menu == 1) {
AddStoreCustomer();
}
This happens because you are using cin>> to read input, which reads until the first whitespace symbol. If you want to read a whole line, consider using std::getline() instead:
getline(cin, customer);

Array input to one class variable c++

I need to create a class of Students where I need to store their name, surname and subjects that they have in uni. How do I need to assign different subjects to different students? User should input it from console. What my class and input should look like? Heres is the code I have so far For example: there are two students Mark Jacobs and John Johny. Mark has 3 subjects: Math, Physics, Geography and John only has 2 Math and Economy.
#include <iostream>
using namespace std;
class Student{
private:
string name;
string surname;
int courseNo;
string subjects[100];
public:
Student(string name = "empty", string surname = "empty")
{
this->name = name + surname;
}
~Student(){
}
void setFullName(string name, string surname){
this->name = name;
this->surname = surname;
}
string getFullName(){
return name + " " + surname;
}
void setSubject(string subjects[100]){
this->subjects[90] = subjects[90];
}
string getSubject(){
return subjects[90];
}
string toString() const
{
return "Studentas: " + this->name;
}
};
int main() {
int number_of_students;
int number_of_subjects = 0;
int choice;
string subjects[90];
string name;
string surname;
cout << "Enter number of students: ";
cin >> number_of_students;
Student Studentas[number_of_students];
cout << "Enter " << number_of_students << " students names and surnames: " << endl;
for (int i = 0; i < number_of_students; i++) {
cin >> name >> surname;
Studentas[i].setFullName(name, surname);
}
for (int i = 0; i < number_of_students; i++) {
cout << i+1 << " Student: " << Studentas[i].getFullName() << endl;
}
cout << "Choose which students subjects you want to enter: ";
cin >> choice;
if(choice == 1){
cout << "Enter " << Studentas[choice-1].getFullName() << " number of subjects: ";
cin >> number_of_subjects;
for (int i = 0; i < number_of_subjects; i++) {
cin >> subjects[i];
Studentas[choice-1].setSubject(subjects);
}
cout << "Studying subjects are: " << endl;
for(int i = 0; i < number_of_subjects; i++){
cout << Studentas[choice-1].getSubject() << endl;
}
}
return 0;
}
I have taken your code changed a little bit, I hope this is what you are looking for
Code:
#include <iostream>
#include <vector>
using namespace std;
class Student {
private:
string name_;
string surname_;
int courseNo_;
std::vector<string> subject_list_;
public:
Student(string name = "empty", string surname = "empty")
{
name_ = name + surname;
}
void setFullName(string name, string surname) {
name_ = name;
surname_ = surname;
}
string getFullName() {
return name_ + " " + surname_;
}
void setSubject(string subject) {
subject_list_.push_back(subject);
}
const std::vector<string>& getSubjects() {
return subject_list_;
}
string toString() const
{
return "Student as: " + name_;
}
};
int main() {
std::vector<Student> student_list;
int number_of_students;
int number_of_subjects = 0;
int choice;
string subject;
string name;
string surname;
cout << "Enter number of students: ";
cin >> number_of_students;
cout << "Enter " << number_of_students << " students names and surnames: " << endl;
for (int i = 0; i < number_of_students; i++) {
cin >> name >> surname;
student_list.push_back(Student(name, surname));
}
int i = 1;
for (auto student : student_list) {
cout << i++ << " Student: " << student.getFullName() << endl;
}
cout << "Choose which students subjects you want to enter: ";
cin >> choice;
if (choice <= number_of_students) {
choice -= 1;
cout << "Enter " << student_list[choice].getFullName() << " number of subjects: ";
cin >> number_of_subjects;
for (int i = 0; i < number_of_subjects; i++) {
cin >> subject;
student_list[choice].setSubject(subject);
}
cout << "Studying subjects are: " << endl;
const auto& subject_list = student_list[choice].getSubjects();
for (auto& subject : subject_list){
cout << subject << endl;
}
}
return 0;
}

Unable to return struct value in c++

I have two text files and the Load function transfers the data from both text files to a single struct (Employee emp[length]) with a const length of 2001. This is because there are 2000 employee details in the text file.
After loading the data into struct, I wanted to search and display employee data using the Select function.
The user will be prompted to choose which employee attribute and keyword that is going to be used for searching. However, I realize that I cannot return a struct(emp[i]) or a string value(emp[i].empId). It will prompt out an error saying
access violation reading location 0x00D2C000
However, I am able to display the string value(emp[i].empId) using cout.
May I know why can I cout the string value but not return it?
Thank you for your help in advance and sorry for my poor English.
const int length = 2001;
struct Employee {
string empId;
string dOB;
string height;
string weight;
string yrOfWork;
string salary;
string allowance;
string name;
string country;
string designation;
string gender;
string lvlOfEdu;
};
Employee emp[length];
void Load();
Employee Select(int k, string s, int c);
int main() {
bool quit = false;
int option;
while (quit != true) { //loop the program unless 7 is chosen
Load();
cout << "1. Add" << endl; //
cout << "2. Delete" << endl;
cout << "3. Select" << endl;
cout << "4. Advanced Search" << endl;
cout << "5. Standard Deviation" << endl;
cout << "6. Average" << endl;
cout << "7. Quit" << endl;
cout << "Please key in an option: ";
cin >> option;
system("cls"); //to refresh the screen
switch (option) {
case 3: {
int search;
string key;
cout << "1. Employee ID" << endl;
cout << "2. Date of Birth" << endl;
cout << "3. Height" << endl;
cout << "4. Weight" << endl;
cout << "5. Years of Working" << endl;
cout << "6. Basic Salary" << endl;
cout << "7. Allowance" << endl;
cout << "8. Employee Name" << endl;
cout << "9. Country" << endl;
cout << "10. Designation" << endl;
cout << "11. Gender" << endl;
cout << "12. Level of Education" << endl;
cout << "Select By: ";
cin >> search;
cout << "Enter keyword: ";
cin >> key;
for (int i = 0; i < length; i++) {
cout << Select(search, key, i).empId;
}
system("pause");
system("cls");
break;
}
}
}
}
Employee Select(int s, string k, int c) {
int result;
int i = c;
switch(s) {
case 1:
result = emp[i].empId.find(k);
if (result >= 0) {
return emp[i];
}
break;
}
}
void Load() {
ifstream inFigures;
inFigures.open("profiles_figures.txt");
ifstream inWords;
inWords.open("profiles_words.txt");
if (inFigures.is_open()) {
int i = 0;
while (!inFigures.eof()) {
inFigures >> emp[i].empId;
inFigures.ignore();
inFigures >> emp[i].dOB;
inFigures.ignore();
inFigures >> emp[i].height;
inFigures.ignore();
inFigures >> emp[i].weight;
inFigures.ignore();
inFigures >> emp[i].yrOfWork;
inFigures.ignore();
inFigures >> emp[i].salary;
inFigures.ignore();
inFigures >> emp[i].allowance;
inFigures.ignore();
i++;
}
}
//inFigures.close();
if (inWords.is_open()) {
int i = 0;
while (!inWords.eof()) {
getline(inWords, emp[i].name);
getline(inWords, emp[i].country);
getline(inWords, emp[i].designation);
inWords >> emp[i].gender;
inWords.ignore();
inWords >> emp[i].lvlOfEdu;
inWords.ignore();
i++;
}
}
//inWords.close();
}
The main problem I think is, what do you return if Select doesn't find anything? The function is supposed to return an employee. You could have a special Employee with a nonsensical empId (e.g. -1) to indicate this, and change
for (int i = 0; i < length; i++)
{
cout << Select(search, key, i).empId;
}
to
for (int i = 0; i < length; i++)
{
Employee selected = Select(search, key, i);
if (selected.empId != -1)
{
cout << Select(search, key, i).empId;
}
}
Alternatively you could alter the Select function so that it returns a pointer Employee * and then return nullptr if there is no match. That is
Employee* Select(int s, string k, int c)
{
int result;
int i = c; // why not just use c directly? Or change the argument to int i?
switch(s)
{
case 1:
result = emp[i].empId.find(k);
if (result >= 0)
{
return &emp[i]; // note taking address, could also write emp + i
}
break; // don't need this with no further cases
}
return nullptr; // reached if no match above
}
Followed later by
for (int i = 0; i < length; i++)
{
Employee* selected = Select(search, key, i);
if (selected != nullptr)
{
cout << Select(search, key, i)->empId; // not pointer indirection
}
}
Really you'd probably want to return a const Employee const*, but that's another topic.
Yet another option is having Select throw an exception if it doesn't find anything, and placing the call to Select(search, key, i); in a try .. catch block. I generally prefer not to use exceptions for control flow like this, but it is another method.