Inserting an object into a C++ Sequential list - c++

For a school programming assignment I built an application that stores a list of objects in a sequential list object. The sequential list class has a method to insert a new object into the list, it checks first to see if the list already has the maximum number of entries allowed and if it does returns an error. For some reason I'm unable to insert a new object into the list (I keep getting the "Max list size exceeded" error) even though there aren't any entries in it to start.
I ran it with a breakpoint to see if the size data member was increasing somehow but that doesn't seem to be the case here.
Please ignore the poor code quality, still just learning... Feel free to make any recommendations :)
Here's the main program:
#include<iostream>
#include<string>
#include "aseqlist.h"
using namespace std;
void PrintByGender (const SeqList& L, char gender)
{
int size = L.ListSize();
int count = 0;
while (count < size)
{
if (gender == L.GetData(count).getGender())
{
L.GetData(count).PrintEmployee();
}
count++;
}
}
int InList (const SeqList& L, char *lname, Employee& Emp)
{
int found = 0;
Emp.setLast(lname);
if (L.Find(Emp) == 1)
{
found = 1;
Emp.PrintEmployee();
}
return found;
}
int main()
{
SeqList obj1;
bool close = false;
string choice = "";
do
{
cout << "Please choose what you would like to do: " << "\n";
cout << "N = New record, D = Delete record, P = Print by gender, S = Search and E = Exit" << "\n";
cin >> choice;
cin.ignore();
if (choice == "n" || choice == "N")
{
string first, last;
int age;
char gen;
double empNum;
cout << "First name: ";
cin >> first;
cout << "Last name: ";
cin >> last;
cout << "Age: ";
cin >> age;
cout << "Gender ('M' Or 'F'): ";
cin >> gen;
cout << "Employee Number: ";
cin >> empNum;
Employee newEmp;
newEmp.ReadEmployee(first, last, age, gen, empNum);
obj1.Insert(newEmp);
}
if (choice == "e" || choice == "E")
{
close = true;
}
if (choice == "p" || choice == "P")
{
char genderSearch;
cout << "Male = M, Female = F";
cin >> genderSearch;
cin.ignore();
PrintByGender(obj1, genderSearch);
}
if (choice == "d" || choice == "D")
{
string last;
cout << "Which employee? (Enter Last Name): ";
cin >> last;
cin.ignore();
Employee emp;
emp.setLast(last);
obj1.Delete(emp);
cout << "Deleted";
}
if (choice == "s" || choice == "S")
{
char lnameSearch;
cout << "Last Name?: ";
cin >> lnameSearch;
cin.ignore();
Employee emp;
char *ptrSearch;
ptrSearch = &lnameSearch;
InList(obj1, ptrSearch, emp);
if (emp.getFirst() != "")
{
emp.PrintEmployee();
}
}
}
while (close != true);
};
And here's the header file for the class declarations:
#include <iostream>
using namespace std;
const int MaxListSize = 6;
// You will need to change the typedef in the following line
// from the data type int to Employee
class Employee
{
public:
Employee();
Employee(string firstName, string lastName, int age, char gender, double employeeNumber);
void ReadEmployee(string firstName, string lastName, int age, char gender, double employeeNumber);
char getGender();
string getFirst();
void Employee::setLast(string lname);
string getLast();
void PrintEmployee();
private:
string LastName;
string FirstName;
int Age;
char Gender;
double EmployeeNumber;
};
typedef Employee DataType;
class SeqList
{
private:
// list storage array and number of current list elements
DataType listitem[MaxListSize];
int size;
public:
// constructor
SeqList(void);
// list access methods
int ListSize(void) const;
int ListEmpty(void) const;
int Find (DataType& item) const;
DataType GetData(int pos) const;
// list modification methods
void Insert(const DataType& item);
void Delete(const DataType& item);
DataType DeleteFront(void);
void ClearList(void);
};
// Class Definition:
// constructor. set size to 0
SeqList::SeqList (void): size(6)
{}
// return number of elements in list
int SeqList::ListSize(void) const
{
return size;
}
// tests for an empty list
int SeqList::ListEmpty(void) const
{
return size == 0;
}
// clears list by setting size to 0
void SeqList::ClearList(void)
{
size = 0;
}
// Take item as key and search the list. return True if item
// is in the list and False otherwise. if found,
// assign the list element to the reference parameter item
bool operator==(Employee A, Employee B)
{
bool isequal = false;
if (A.getLast() == B.getLast())
isequal = true;
return isequal;
}
int SeqList::Find(DataType& item) const
{
int i = 0;
if (ListEmpty())
return 0; // return False when list empty
while (i < size && !(item == listitem[i]))
i++;
if (i < size)
{
item = listitem[i]; // assign list element to item
return 1; // return True
}
else
return 0; // return False
}
// insert item at the rear of the list. terminate the program
// if the list size would exceed MaxListSize.
void SeqList::Insert(const DataType& item)
{
// will an insertion exceed maximum list size allowed?
if (size+1 > MaxListSize)
{
cout << "Maximum list size exceeded" << endl;
exit(1);
}
// index of rear is current value of size. insert at rear
listitem[size] = item;
size++; // increment list size
}
// search for item in the list and delete it if found
void SeqList::Delete(const DataType& item)
{
int i = 0;
// search for item
while (i < size && !(item == listitem[i]))
i++;
if (i < size) // successful if i < size
{
// shift the tail of the list to the left one position
while (i < size-1)
{
listitem[i] = listitem[i+1];
i++;
}
size--; // decrement size
}
}
// delete element at front of list and return its value.
// terminate the program with an error message if the list is empty.
DataType SeqList::DeleteFront(void)
{
DataType frontItem;
// list is empty if size == 0
if (size == 0)
{
cout << "Attempt to delete the front of an empty list!" << endl;
exit(1);
}
frontItem = listitem[0]; // get value from position 0.
Delete(frontItem); // delete the first item and shift terms
return frontItem; // return the original value
}
// return value at position pos in list. if pos is not valid
// list position, teminate program with an error message.
DataType SeqList::GetData(int pos) const
{
// terminate program if pos out of range
if (pos < 0 || pos >= size)
{
cout << "pos is out of range!" << endl;
exit(1);
}
return listitem[pos];
}
Employee::Employee()
{
FirstName = "";
LastName = "";
Age = 0;
/*Gender = "";*/
EmployeeNumber = 0;
};
Employee::Employee(string firstName, string lastName, int age, char gender, double employeeNumber)
{
FirstName = firstName;
LastName = lastName;
Age = age;
Gender = gender;
EmployeeNumber = employeeNumber;
};
void Employee::PrintEmployee()
{
cout << "First Name: " << FirstName << "\n";
cout << "Last Name: " << LastName << "\n";
cout << "Age: " << Age << "\n";
cout << "Gender: " << Gender << "\n";
cout << "Employee Number :" << EmployeeNumber << "\n" << "\n";
};
void Employee::ReadEmployee(string firstName, string lastName, int age, char gender, double employeeNumber)
{
FirstName = firstName;
LastName = lastName;
Age = age;
Gender = gender;
EmployeeNumber = employeeNumber;
};
char Employee::getGender()
{
return Gender;
}
string Employee::getFirst()
{
return FirstName;
}
string Employee::getLast()
{
return LastName;
}
void Employee::setLast(string lname)
{
LastName = lname;
}

Problem in the constructor:
SeqList::SeqList (void): size(6)
size is being initialized as 6.
Other suggestions. Don't put using namespace std; in a header file. Better yet, don't put using namespace std; anywhere.
Why is "using namespace std" considered bad practice?

// constructor. set size to 0
SeqList::SeqList (void): size(6)
{}
This is wrong. Should be so:
// constructor. set size to 0
SeqList::SeqList (void): size(0)
{}

Related

Creating a vector in class then using class object in function not working

I have a class Employees. I'm trying to make the user insert and delete an employee but it's not working. The size of the vectors should be 500.
class Employees{
public:
int maxx = 500;
vector<string> Surname;
vector<string> FirstName;
vector<string> birthdate;
int vacation[500];
public:
Employees() : Surname(500) {}
};
This is the function that inserts, but printing elements of the vectors is not working at all:
void Process(Employees ZZ){
string dateyear;
string datemonth;
string dateday;
int dateyear1;
int datemonth1;
int dateday1;
int Realage;
int Vacationi = 0;
for(int i = 0; i < 500; i++) {
string s;
cin >> s;
string d;
cin >> d;
string c;
cin >> c;
ZZ.Surname.push_back(s);
ZZ.FirstName.push_back(d);
ZZ.birthdate.push_back(c);
cout << endl << ZZ.Surname[1] << endl;
}
Now the delete function, if I input a string then search for it in the vector then get his index then delete, but the vector doesn't update any values.
void DeleteEmployee(Employees ZZ){
cout<< endl << ZZ.Surname[1] << endl ;
for (int i = 0; i < ZZ.Surname.size(); i++){
cout << ZZ.Surname[i] ;
}
cout << " delete employee";
string delete1;
cin >> delete1;
auto it = std::find(ZZ.Surname.begin(), ZZ.Surname.end(), delete1);
if (it == ZZ.Surname.end())
{
cout<< " name not in vector " << endl;
}
else
{
//auto index = distance(Names.begin(), find(Names.begin(), Names.end(), old_name_)));
//ZZ.Surname.erase(ZZ.Surname.begin()+index) ;
}
}
This is the main function, also the values of the vector are not printing:
int main()
{
Employees ZZ;
Process(ZZ);
DeleteEmployee(ZZ);
cout << "fyccck";
for (int i = 0; i < ZZ.Surname.size(); i++){
cout << ZZ.Surname[i] ;
}
}
There are a lot of things wrong with this code. But the particular issue you are asking about is caused by your functions passing the Employees object by value, so a copy is made, and any changes you make to the copy are not reflected in the original object in main().
You need to change the parameters to pass the Employees object by reference instead:
void Process(Employees &ZZ)
void DeleteEmployee(Employees &ZZ)
That being said, the whole design of the code is not good in general. The vectors are not being kept in sync properly, and for that matter you are using more vectors then you actually need, 1 single vector will suffice. And Process() and DeleteEmployee() should be members of the Employees class, not separate functions. And they are both accessing out-of-bounds of the Surname vector.
I would suggest completely rewriting the code from scratch, for instance something more like this:
struct Employee{
string Surname;
string FirstName;
string BirthDate;
int Vacation;
string DisplayName() const { return Surname + ", " + FirstName; }
};
class Employees{
public:
static const int maxx = 500;
vector<Employee> employees;
Employees() { employees.reserve(maxx); }
bool Add(const Employee &e);
bool Delete(string Surname, string FirstName);
};
bool Employees::Add(const Employee &e) {
if (employees.size() < maxx) {
employees.push_back(e);
return true;
}
return false;
}
bool Employees::Delete(string Surname, string FirstName) {
auto it = std::find_if(employees.begin(), employees.end(),
[&](const Employee &e){
return e.Surname == Surname && e.FirstName == FirstName;
}
);
if (it != employees.end()) {
employees.erase(it);
return true;
}
return false;
}
int main()
{
Employees ZZ;
for(int i = 0; i < Employees::maxx; ++i) {
Employee e;
cin >> e.Surname;
cin >> e.FirstName;
cin >> e.BirthDate;
e.Vacation = 0;//cin >> e.Vacation;
ZZ.Add(e);
cout << endl << e.DisplayName() << endl;
}
cout << " delete employee";
string Surname, FirstName;
if (cin >> Surname >> FirstName) {
if (ZZ.Delete(Surname, FirstName)) {
cout << " name deleted from vector " << endl;
} else {
cout << " name not in vector " << endl;
}
}
cout << "fyccck";
for (auto &e : ZZ.employees) {
cout << e.DisplayName() << endl;
}
return 0;
}

Reading data from file into queue in c++

I am having trouble figuring out how to get my input data into my queue... I am so close to getting this to work right.
I know I am just confused about how things are working. I have used example code and my instructions to come up with a working program that appears to be working correctly (other than not actually putting my input file data into the queue). I bypassed the function I was trying to make for this. In addition to this, I was trying to write a function to remove an employee from the queue (which I think does work), but I am not sure I was able to get it right...
I have not taken a programming class for over 10 years and really would love to get any help in understanding what I am doing and getting that darn data into the queue.
Below is my main driver file. I will provide my header file code if needed. Thanks in advance for any help you can provide on this.
//Program Assignment #3
//Creates Queue as a Linked Structure
#include<iostream>
#include<string>
#include<fstream>
#include"Employee.h"
#include"LinkedQ.h"
using namespace std;
struct Node
{
LinkedQ nodeQ;
Employee EmpNumber;
Employee LastName;
Employee FirstName;
Employee ServiceYears;
};
void loadFile(LinkedQ &);
void addEmp(LinkedQ &);
void delEmp(LinkedQ &);
int main()
{
LinkedQ empList;
int choice;
int numIn, yearsIn;
string LastName;
string FirstName;
LinkedQ empIn;
ifstream input;
input.open("Employee.txt");
while (input)
{
input >> numIn >> LastName >> FirstName >> yearsIn;
if (input)
{
cout << "this is where we load data from the file into the queue\n";
system("pause");
//empIn.Enqueue(numIn, LastName, FirstName, yearsIn);
//empList.addEmp(empIn);
}
}
input.close();
do
{
//display menu
system("cls");
cout << "\t\tMenu: \n"
<< "\t1. Add Employee\n"
<< "\t2. Remove Employee\n"
<< "\t3. Count of Employees\n"
<< "\t4. Quit\n\n";
cout << "Enter your choice and press return: ";
cin >> choice;
switch (choice)
{
case 1:
addEmp(empList); // call to function to add an employee to the queue
break;
case 2:
delEmp(empList); // call to fucntion to remove an employee from the queue
break;
case 3:
cout << endl << "Count of Employees: "
<< empList.GetLength() << endl; // See how many employees are in the queue
system("pause");
break;
case 4:
cout << "End of Program"; // End Program
break;
default:
cout << "Not a valid choice!" << endl;
cout << "Choose Again."; // Handling incorrect inputs
system("pause");
break;
}
} while (choice != 4); // If choice is not 4, continue running program
return 0;
}
//***********************************
//Loads the file (having trouble figuring out how to implement this part)
//***********************************
void loadFile(Employee &empList)
{
int numIn, yearsIn;
string LastName;
string FirstName;
LinkedQ empIn;
ifstream input;
input.open("Employee.txt");
while (input)
{
input >> numIn >> LastName >> FirstName >> yearsIn;
if (input)
{
cout << "this is where we load data from the file into the queue";
//empIn.setFields(numIn, LastName, FirstName, yearsIn);
//empList.addEmp(empIn);
}
}
input.close();
}
//***************************************
//add an employee
//***************************************
void addEmp(LinkedQ &empList)
{
Employee newEmp;
newEmp.user();
empList.Enqueue(newEmp);
}
//****************************************
//remove a employee
//****************************************
void delEmp(LinkedQ &empList)
{
Employee EmpToRemove;
int empNum;
// bool successful;
cout << "Please enter EMPLOYEE NUMBER of employee to remove:";
cin >> empNum;
EmpToRemove.setEmpNumber(empNum);
empList.Dequeue(EmpToRemove);
//successful = empList.Dequeue(EmpToRemove);
//if (successful == true)
//{
cout << "Removed" << endl << endl;
system("pause");
//}
//else
//{
// cout << "Emp Not found" << endl << endl;
//}
}
Here is the LinkedQ implementation file:
//LinkedQ class
#include "LinkedQ.h"
#include <cstddef>
#include <new>
struct NodeType
{
Employee info;
NodeType* next;
};
LinkedQ::LinkedQ(void)
{
newNode = nullptr;
front = NULL;
rear = NULL;
length = 0;
}
void LinkedQ::MakeEmpty()
{
NodeType* tempPtr;
while (front != NULL)
{
tempPtr = front;
front = front->next;
delete tempPtr;
}
rear = NULL;
}
LinkedQ::~LinkedQ(void)
{
MakeEmpty();
}
bool LinkedQ::IsFull() const
{
NodeType* location;
try
{
location = new NodeType;
delete location;
return false;
}
catch (std::bad_alloc exception)
{
return true;
}
}
bool LinkedQ::IsEmpty() const
{
return (front == NULL);
}
void LinkedQ::Enqueue(Employee newItem)
{
if (IsFull())
cout << "Queue is Full";
// throw FullQueue();
else
{
NodeType* newNode;
newNode = new NodeType;
newNode->info = newItem;
newNode->next = NULL;
if (rear == NULL)
{
front = newNode;
}
else
{
rear->next = newNode;
}
rear = newNode;
length++;
}
}
void LinkedQ::Dequeue(Employee& item)
{
if (IsEmpty())
{
//throw EmptyQueue();
cout << "Queue is empty";
}
else
{
NodeType* tempPtr;
tempPtr = front;
item = front->info;
front = front->next;
if (front == NULL)
{
rear = NULL;
}
delete tempPtr;
length--;
}
}
int LinkedQ::GetLength() const
{
return length;
}
And here is the Employee implementation file:
//employee Class
#include"Employee.h"
//Constructor
Employee::Employee()
{
EmpNum = 0;
}
//setters
void Employee::setEmpNumber(int eNum)
{
EmpNum = eNum;
}
void Employee::setEmpName(string LName)
{
LastName = LName;
}
void Employee::setEmpFirstName(string FName)
{
FirstName = FName;
}
void Employee::setYearsService(int years)
{
YearsService = years;
}
void Employee::setFields(int num, string LN, string FN, int years)
{
EmpNum = num;
LastName = LN;
FirstName = FN;
YearsService = years;
}
void Employee::user()
{
string inputString;
int intNumber;
cout << "Employee Number ";
cin >> intNumber;
while (intNumber <= 0)
{
cout << "Employee Number ";
cin >> intNumber;
}
EmpNum = intNumber;
cout << "Last Name: ";
cin >> inputString;
LastName = inputString;
cout << "First Name: ";
cin >> inputString;
FirstName = inputString;
cout << "Years of Service: ";
cin >> intNumber;
while (intNumber < 0)
{
cout << "Years of Service ";
cin >> intNumber;
}
cout << endl;
YearsService = intNumber;
}
//getters
const int Employee::getEmpNumber()
{
return EmpNum;
}
const string Employee::getLastName()
{
return LastName;
}
const string Employee::getFirstName()
{
return FirstName;
}
const int Employee::getYearsService()
{
return YearsService;
}
//overloads
bool Employee::operator == (const Employee &right)
{
bool status;
if ( EmpNum == right.EmpNum)
status = true;
else
status = false;
return status;
}
bool Employee::operator != (const Employee &right)
{
bool status;
if (EmpNum != right.EmpNum)
status = true;
else
status = false;
return status;
}
I think the parameter of loadFile should be of type LinkedQ, which, if I understand it correctly, is the queue class/struct, and the empIn variable should be of type Employee.
Edit:
The method you call on the empList object should be Enqueue, instead of addEmp.

c++ error: 'std::string' has no member

I am creating a directory program that prompts a user for a file name and reads the file into a string array. I'm have trouble in my SearchFirstName function. I get an error:'std::string' has no member named 'userRecord'. I'm not sure how to fix this because userRecord is declared.
Header
#include<string>
using namespace std;
enum Title {Mr, Mrs, Ms, Dr, NA};
struct NameType {
Title title;
string firstName;
string lastName;
};
struct AddressType {
string street;
string city;
string state;
string zip;
};
struct PhoneType {
int areaCode;
int prefix;
int number;
};
struct entryType {
NameType name;
AddressType address;
PhoneType phone;
};
const int MAX_RECORDS = 50;
Code
// string bookArray[MAX_RECORDS];
entryType bookArray[MAX_RECORDS]; //Solution
int bookCount = 0;
void OpenFile(string& filename, ifstream& inData)
{
do {
cout << "Enter file name to open: ";
cin >> filename;
inData.open(filename.c_str());
if (!inData)
cout << "File not found!" << endl;
} while (!inData);
if(inData.is_open())
{
for(int i=0; i<MAX_RECORDS;i++)
{
inData>> bookArray[bookCount];
++bookCount;
}
}
}
void SearchFirstName(ifstream& inData)
{
entryType userRecord; // Declaration of userRecord
string searchName;
string normalSearchName, normalFirstName;
char choice;
bool found = false;
cout << "Enter first name to search for: ";
cin >> searchName;
for(int i = 0; i < bookCount; ++i){
normalFirstName = NormalizeString(bookArray[i].userRecord.name.firstName);
// Convert retrieved string to all uppercase
if (normalFirstName == normalSearchName) { // Requested name matches
PrintRecord(bookArray[i].userRecord.name.firstName);
cout << "Is this the correct entry? (Y/N)";
cin >> choice;
choice = toupper(choice);
cout << endl;
if (choice == 'Y') {
found = true;
break;
}
}
}
// Matching name was found before the end of the file
if (inData && !found){
cout << "Record found: " << endl;
PrintRecord(userRecord);
cout << endl;
}
else if (!found) // End of file. Name not found.
{
cout << searchName << " not found!" << endl << endl;
}
// Clear file fail state and return to beginning
inData.clear();
inData.seekg(0);
}
string bookArray[MAX_RECORDS];
bookArray is of type string.It should be
entryType bookArray[MAX_RECORDS];
Also
normalFirstName = NormalizeString(bookArray[i].userRecord.name.firstName);
bookArray[i] cannot have userRecord as a member.userRecord is variable that you have declared.
It should be
normalFirstName = NormalizeString(bookArray[i].name.firstName);

C++ Arrays and Reading from file

I'm creating an address book program that allow user to search by first name, last name,phone number and address. The user is prompted to enter a file name and the file is read into an array. I'm having trouble modifying by existing SearchFirstName function to loop through array. I have read over this topic multiple times I'm just not understanding it. Any help would be greatly appreciated.
File
Susan, Smith, 123 456 789
101 Main Street
Bob, Smith, 567 345 9076
456 Market Street
Header File
#include<string>
using namespace std;
enum Title {Mr, Mrs, Ms, Dr, NA};
struct NameType {
Title title;
string firstName;
string lastName;
};
struct AddressType {
string street;
string city;
string state;
string zip;
};
struct PhoneType {
int areaCode;
int prefix;
int number;
};
struct entryType {
NameType name;
AddressType address;
PhoneType phone;
};
const int MAX_RECORDS = 50;
struct addressBookType {
entryType record[MAX_RECORDS];
int numEntries;
};
Code
string bookArray[MAX_RECORDS];
int main()
{
entryType userRecord;
string filename;
ifstream inData;
char searchOption;
OpenFile(filename, inData);
MainMenu(inData, filename);
return 0;
}
void OpenFile(string& filename, ifstream& inData)
{
do {
cout << "Enter file name to open: ";
cin >> filename;
inData.open(filename.c_str());
if (!inData)
cout << "File not found!" << endl;
} while (!inData);
if(inData.is_open())
{
for(int i=0; i<MAX_RECORDS;i++)
{
inData>> bookArray[i];
}
}
}
// Searches passed file stream for a first name read from the user
void SearchFirstName(ifstream& inData)
{
string searchName;
entryType userRecord;
string normalSearchName, normalFirstName;
char choice;
bool found = false;
cout << "Enter first name to search for: ";
cin >> searchName;
normalSearchName = NormalizeString(searchName); // Convert name to all uppercase
// Loop through all records in the file
while (GetRecord(inData, userRecord)){
normalFirstName = NormalizeString(userRecord.name.firstName); // Convert retrieved string to all uppercase
if (normalFirstName == normalSearchName) { // Requested name matches
PrintRecord(userRecord);
cout << "Is this the correct entry? (Y/N)";
cin >> choice;
choice = toupper(choice);
cout << endl;
if (choice == 'Y') {
found = true;
break;
}
}
}
// Matching name was found before the end of the file
if (inData && !found){
cout << "Record found: " << endl;
PrintRecord(userRecord);
cout << endl;
}
else if (!found) // End of file. Name not found.
{
cout << searchName << " not found!" << endl << endl;
}
// Clear file fail state and return to beginning
inData.clear();
inData.seekg(0);
}
My attempt
void SearchFirstName(ifstream& inData)
{
string searchName;
entryType userRecord;
cout << "Enter first name to search for: ";
cin >> searchName;
string newSearchName = NormalizeString(searchName);
string upFirst = NormalizeString(userRecord.name.firstName);
for (int i=0;i<MAX_RECORDS;i++)
{
while(newSearchName == upFirst)
{
if (bookArray[i]== upFirst)
{
cout<<"Name Found";
cout <<bookArray[i]; //test case
}
}
}
}
Create your array, in this case it'll be an std::vector because that is more simple to use, by running your GetRecord function inside of a while loop and appending the result to the vector w/vector_variable_name.push_back(NormalizeString(value_returned_from_GetRecord));. The NormalizeString part is so you don't have to call it billions of times later.
Pass in your array like so void SearchFirstName(std::vector<entryType> *in_data_arr>)
Change your while loop to a for loop: for (int i = 0; i < in_data_arr.size(); i++) {
Inside the loop change normalSearchName = NormalizeString(searchName); to normalSearchName = in_data_arr[i].name.firstName;
And from there it should generally be identical.

How to fix this code

Please, how to fix this code
[Error] a function-definition is not allowed here before '}' token
[Error] expected '}' at the end of input
I don't know what's the problem with my code even though I've already checked the compiler errors
#include<iostream>
using namespace std;
struct name_type
{
string first,middle,last;
};
struct SD
{
name_type name;
float grade;
};
const int MAX_SIZE = 35;
int isFull(int last) {
if(last == MAX_SIZE - 1) {
return(1);
}
else {
return(0);
}
}
int isEmpty(int last) {
if(last < 0) {
return(1);
}
else {
return(0);
}
}
main()
{
SD SD2[MAX_SIZE];
int last = -1;
if(isEmpty(last))
{
cout << "List is empty\n";
}
for (int a=0; a <35; a++)
{
cout << "Enter first name:.....";
cin >> SD2[a].name.first;
cout << "Enter middle name:....";
cin >> SD2[a].name.middle;
cout << "Enter last name:......";
cin >> SD2[a].name.last;
cout << "Enter your grade:.....";
cin >> SD2[a].grade;
cout << '\n';
}
system("cls");
cout << "1 - Add";
cout << "2 - Delete";
cout << "3 - Search";
cout << "4 - Print";
cout << "5 - Exit";
string lname, fname;
int choice, search;
cin >> choice;
if(choice == 3) {
cin >> fname;
cin >> lname;
int index = search;
(SD2, lname, fname, last);
if (index > 0) {
cout << "ERROR\n";
}
else {
cout << "The grade of " << lname << "," << fname << "is " << SD2[index].grade;
}
}
int search(SD list [], string search_lname, string search_fname, int last) {
int index;
if(isEmpty(last)==1) {
cout << "\nThe list is Empty!";
}
else {
index = 0;
while(index!= last+1 && list[index].name.first != search_fname && list[index].name.last != search_lname) {
++index;
}
if(index != last + 1) {
cout << "\nItem Requested is Item" << index + 1 << ".";
return index;
}
else {
cout << "\n Item Does Not Exist.";
}
}
return -1; // list is empty or search item does not exist
}
}
One of the problems is in your declaration of the main function:
main()
In c++, the main() function must have a return type of int. Sin you have not specified any data type for the return value of main(), it sets the return data type to void, which is produces the error just before main(). To learn and understand more about main() for C++, visit the following link Main Function.
To sort this, change the above line of code to:
int main() // notice that the return type here is int. This is required in c++
Another thing: in these lines:
int index = search;
(SD2, lname, fname, last);
Over here, you want to pass SD2, lname, fname and last to the search() function. However, your syntax is wrong. The function and its parameters when called cannot be split by a semicolon, because a semicolon terminates the statement. Therefore, the compiler sees search as a variable, not a function. This along with the statement following it cause the error. You should change those 2 lines to:
int index = search(SD2, lname, fname, last); // this is proper syntax to call a function.
Also, you need to take out search() from inside the main() function and place it above the main() function. That is also causing an error.