Alternative to strcmp() to alphabetically sort strings - c++

stuType Class:
#include<iostream>
#include<cstring>
using namespace std;
#ifndef STUTYPE
#define STUTYPE
class stuType {
private:
string fname;
string lname;
string social;
float gpa;
public:
stuType(void) {
fname = "no_fname";
lname = "no_lname";
social = "no_social";
gpa = 0.0;
}
stuType(string fname_in, string lname_in, string social_in, float gpa_in) {
fname = fname_in;
lname = lname_in;
social = social_in;
gpa = gpa_in;
}
~stuType() {
//Nothing needs to be added here.
}
void set_fname(string new_fname) {
fname = new_fname;
}
void set_lname(string new_lname) {
lname = new_lname;
}
void set_ssn(string new_ssn) {
social = new_ssn;
}
void set_gpa(float new_gpa) {
gpa = new_gpa;
}
string get_fname(void) {
return fname;
}
string get_lname(void) {
return lname;
}
string get_ssn(void) {
return social;
}
float get_gpa(void) {
return gpa;
}
friend istream & operator>>(istream &in, stuType &stu) {
in>>stu.fname;
in>>stu.lname;
in>>stu.social;
in>>stu.gpa;
return in;
}
};
#endif
Sort.cpp:
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<cstring>
#include"stuType.h"
using namespace std;
/*Loads the elements of the object instance with data from the input file.*/
void load(istream &input, stuType Student[], int *size);
/*Used in combination with the shellSort method to exchange the values of two variables in the class object.*/
void exchange(stuType &a, stuType &b);
/*Sorts the objects in ascending order by comparing the values of the lname strings between object indices.*/
void shellSort(stuType Student[], int size);
int main() {
stuType Student[10];
int size;
char inputFile[200];
char outputFile[200];
ifstream input;
ofstream output;
cout<<"[INPUT_FILE]: ";
cin>>inputFile;
cout<<"[OUTPUT_FILE]: ";
cin>>outputFile;
input.open(inputFile);
output.open(outputFile);
if (input.fail()) {
cerr<<"\n[FILE] Error opening '"<<inputFile<<"'"<<endl;
exit(1);
}
if (output.fail()) {
cerr<<"\n[FILE] Error opening '"<<outputFile<<"'"<<endl;
exit(1);
}
load(input, Student, &size);
shellSort(Student, size);
return 0;
}
void load(istream &input, stuType Student[], int *size) {
int length = 0, i = 0;
float gpa;
string social;
string fname;
string lname;
while(input >> social >> fname >> lname >> gpa) {
cout<<"[Node::Load] Setting 'social' for index ["<<i<<"] to "<<social<<endl;
Student[i].set_ssn(social);
cout<<"[Node::Load] Setting 'fname' for index ["<<i<<"] to "<<fname<<endl;
Student[i].set_fname(fname);
cout<<"[Node::Load] Setting 'lname' for index ["<<i<<"] to "<<lname<<endl;
Student[i].set_lname(lname);
cout<<"[Node::Load] Setting 'gpa' for index ["<<i<<"] to "<<gpa<<endl;
Student[i].set_gpa(gpa);
cout<<"[Node::Load] Incrementing 'length'..."<<endl;
length++;
cout<<"[Node::Load] Incrementing 'i'..."<<endl;
i++;
}
cout<<"==================================="<<endl;
for (int i = 0; i<length; i++) {
cout<<"[ENTRY] Index: "<<i<<" | SSN: "<<Student[i].get_ssn()<<" | fname: "<<Student[i].get_fname()<<" | lname: "<<Student[i].get_lname()<<" | gpa: "<<Student[i].get_gpa()<<endl;
}
cout<<"==================================="<<endl;
*size = length;
}
void exchange(stuType &a, stuType &b) {
stuType *temp;
*temp = a;
a = b;
b = *temp;
delete temp;
}
void shellSort(stuType Student[], int size) {
int gap = size/2;
bool passOK;
while(gap>0) {
passOK = true;
for(int i = 0; i<size-gap; i++) {
if (strcmp(Student[i].get_lname(), Student[i+gap].get_lname)>0) {
cout<<"[Node::Sort] Exchanging Index ["<<i<<"] with Index ["<<i+gap<<"]..."<<endl;
exchange(Student[i], Student[i+gap]);
passOK = false;
} else if (strcmp(Student[i].get_lname(), Student[i+gap].get_lname())==0) {
if (strcmp(Student[i].get_fname(), Student[i+gap].get_fname())>0) {
cout<<"[Node::Sort] Exchanging Index ["<<i<<"] with Index ["<<i+gap<<"]..."<<endl;
exchange(Student[i], Student[i+gap]);
passOK = false;
}
}
}
if (passOK) {
gap /= 2;
}
}
}
strcmp() expects to receive a character array to do the comparison, but since I am using strings, I cannot do that. What is an alternative? The variable 'lname' needs to be compared and should return true if Student[i].get_lname() is greater than Student[i+gap].get_lname(). The exchange function will then be called and exchange the values of the object's local variables. The objects should be sorted in ascending order based on the value of the 'lname' variable and the 'fname' variable should only be referenced if the two 'lname's being compared are the same.

C++ strings provide implementations of operators < and >, so you can use them instead of strcmp:
std::string a = "hello";
std::string b = "world";
if (a < b) {
cout << a << " is less than " << b << endl;
}

Related

Why do I get a segmentation fault when fetching this variable?

I am pulling names as strings from a file, create a Person *p object, and put it into an array.
Then to search the array for a name but when I try to fetch the name I get a segmentation fault.
Why is this segmentation fault happening, and what can I do to fix it?
#include <iostream>
#include <string>
using namespace std;
class Person {
private:
string firstName;
string lastName;
string phoneNumber;
public:
Person();
Person(string f, string l, string n);
~Person(void);
void setName()
{
}
string getFirstName()
{
return firstName;
}
string getLastName()
{
return lastName;
}
string getNumber() { return phoneNumber; }
void print();
};
Array creation.
{
ifstream file;
file.open("phonebook.txt");
if (!file.is_open()) //Check for File Error.
{
cerr << "Failed to open file" << endl;
exit(1);
}
//Get Array Size
string line;
while (getline(file, line))
{
count++;
}
file.close();
//Create an array
Person *arrList[count];
buildArray(arrList, count);
if (uInput == "a" || uInput == "A") //To add
{
int x = addPerson();
if (x == 1)
{
count++;
}
delete[] arrList;
}
void buildArray(Person *arr[], int size)
{
string f, l, n;
ifstream file;
file.open("phonebook.txt");
for (int i = 0; i < size; i++)
{
file >> f >> l >> n;
Person *p = new Person(f, l, n);
arr[i] = p;
delete p;
}
}
The search, This is the part that has the trouble. I have tried a few different things including creating 2 Persons, and comparing their parts but whenever it goes into the .h it can not return the name.
if (uInput == "s" || uInput == "S")
{ //To Search
string f, l;
cout << "Find Who (Firstname Lastname) " << endl;
cin >> f >> l;
Person *n = new Person(f, l, "");
int i = 0;
bool found = false;
while (i <= count && found == false)
{
Person *p = new Person("", "", "");
p = arrList[i];
if (p->getFirstName() == n->getFirstName() && p->getLastName() == n->getLastName())
{
arrList[i]->print();
found = true;
delete p;
delete n;
}
i++;
}
while (i == count && found == false)
{
cout << "No results found. " << endl;
found = true;
}
}

Reading from file C++

I need to read this txt file but I don't understand what I'm doing wrong?
http://pastebin.com/gPVbuvhb Here's my reading function
void Read(School & snew){
string school, name, group;
Student S;
ifstream fd(CD);
getline(fd, school, ';');
S.SetSchool(school);
cout << S.GetSchool() << endl;
while(!fd.eof()){
getline(fd, name, ',');
fd >> ws;
getline(fd, group, ' ');
int Paz[Student::M];
int kiek = 0;
while(fd.peek()!= '\n' && !fd.eof()){
fd >> Paz[kiek++];
}
fd.ignore();
}
fd.close();
}
Here's my Student class
class Student{
public:
static const int M = 5;
private:
string school, name, group;
int *Marks; // dynamic array of student marks
int nmax; // max size of array
int n; // current size of array
void IncreaseCapasity(int kiek);
public:
Student(int nmax = 0);
~Student();
void SetMarks(int mark);
void SetSchool(string school);
void SetName(string name);
void SetGroup(string group);
int GetMark(int i){return Marks[i];}
string GetSchool(){return school;}
string GetName(){return name;}
string GetGroup(){return group;}
int GetN(){return n;}
};
Student::Student(int nmax):Marks(NULL), n(n), nmax(nmax){
if(nmax > 0){
Marks = new int[nmax];
}
}
Student::~Student(){
if(Marks){
delete [] Marks;
Marks = NULL;
}
}
void Student::IncreaseCapasity(int kiek){ // maybe this function is incorrect?
if(kiek > nmax){ // if array increasing
int *SNew = new int [kiek];
for(int i=0; i<n; i++)
SNew[i] = Marks[i];
delete [] Marks;
Marks = SNew;
nmax = kiek;
}if(kiek < nmax){ // if array decreasing
int *SNew = new int [kiek];
for(int i=0; i<kiek; i++)
SNew[i] = Marks[i];
delete [] Marks;
Marks = SNew;
n = nmax = kiek;
}
}
void Student::SetMarks(int mark){
if(n == nmax) IncreaseCapasity(n + M);
Marks[n] = mark;
n++;
}
void Student::SetSchool(string school){
this->school = school;
}
void Student::SetName(string name){
this->name = name;
}
void Student::SetGroup(string group){
this->group = group;
}
when I'm reading int values fd >> Paz[kiek++]; I get this error
Unhandled exception at 0x571121F8 (msvcp110d.dll) in ConsoleApplication1.exe: 0xC0000005: Access violation reading location 0x0000000D.
getline(fd, school, ';');
reads from the fd stream, stopping at first occurence of ';'. Since there is no ';' in your file, it reads whole file into school string.
What you actually want to do is to parse your file line by line, constructing instance of istringstream using each line:
std::string line;
while (std::getline(fd, line)) {
if (line.empty())
continue;
std::istringstream is(line);
std::string name, group;
if (std::getline(is, name, ',') && std::getline(is, group, ',')) {
std::cout << "Name: " << name << " Group: " << group << std::endl;
}
}
just don't forget to #include <sstream>.
Also note that:
while (!fd.eof()) {
std::getline(...);
// relying on getline call being successful here
}
is not safe, just use its return value directly.

Deleting a record from array of pointers of my own class type

I have created an Employee class:
class Employee {
private:
int idNumber;
string name, department, position;
public:
Employee() {
idNumber = 0;
name = department = position = "";
}
Employee(string n, int idn) {
name = n;
idNumber = idn;
department = position = "";
}
Employee(string n, int idn, string dep, string pos) {
name = n;
idNumber = idn;
department = dep;
position = pos;
}
void setName(string n) {
name = n;
}
void setidNumber(int idn) {
idNumber = idn;
}
void setDepartment(string dep) {
department = dep;
}
void setPosition(string pos) {
position = pos;
}
string getName() {
return name;
}
int getidNumber() {
return idNumber;
}
string getDepartment() {
return department;
}
string getPosition() {
return position;
}
};
Now, i created a 2D array of Pointers of type Employee:
int n=2;
Employee **p = new Employee * [n];
for (int i=0; i < n; i++)
p[i] = new Employee;
I stored two records successfully as under:
Name ID Number Department Position
FS 30 CS BS
AT 27 CS BS
I have this code to delete the record of Employees:
string del_name;
int flag = 0;
cin.ignore();
cout << "Enter name: ";
getline(cin, del_name);
for (int i=0; i < n; i++) {
while (del_name == p[i]->getName() && i < n) {
if (del_name == p[i]->getName()) {
delete p[i];
p[i] = NULL;
--k;
++flag;
cout << "Record deleted." << endl;
break;
}
else
{
flag = 0;
}
}
}
if (flag == 0)
cout << "No record found having name " << del_name << "." << endl;
Now, What's the problem:
If a record is found at multiple times. It deletes successfully even if all the records gets deleted.
But if ALL the records are unique and I delete the records one by one and all the records get deleted in this way then the program gets terminated.
Also, is there any other optimized approach to delete records without using VECTORS.
I hope i have clearly explained my problem. I can provide further details if needed.
Thank you for your time
First, usage of std::vector<> or some other container object is the way to go about this. If you can write code that beats (in terms of speed) written by professional library writers, then go ahead.
Second, what is your goal? If it's to simply deallocate entries in that array depending on some criteria, the loop you wrote is overly complex.
bool recordDeleted = false;
for (int i=0; i < n; ++i)
{
if (del_name == p[i]->getName())
{
delete p[i];
p[i] = NULL;
recordDeleted = true;
}
}
if ( !recordDeleted )
{
// record not found
}

Unable to access members of a class; SegFault

I have a program where I am setting up a closed hash table. In each Element of the Hash table, there is a Student class which holds varies members (name, id, year, etc.). I am simply trying to print out what has been added to my array, but I keep getting a SegFault, and I don't know why. It is only in my print function, though. I have copied the line of code to my other functions or put them in different classes, and they work there, but not when I try to print from my print function. I am at the end of my rope, trying to figure out why I can access the memory location of each member, but not it's actual value.
Here is my program:
main.cpp:
using namespace std;
#include <cstdlib>
#include "hash.h"
int main()
{
string temp1;
string temp2;
string temp3;
string temp4;
string temp5;
string temp6;
Hash h;
do{
cout << "set> ";
cin >> temp1;
//Checking for quit command.
if(temp1.compare("quit") == 0)
{
return 0;
}
//checking for add command.
else if(temp1.compare("add") == 0)
{
cin >> temp2;
cin >> temp3;
cin >> temp4;
cin >> temp5;
cin >> temp6;
Student *s1 = new Student(temp2, temp3, temp4, temp5, temp6);
Element e1(s1);
h.add(e1);
}
//checking for remove command.
else if(temp1.compare("remove") == 0)
{
int r;
cin >> r;
h.remove(r);
}
//checking for print command.
else if(temp1.compare("print") == 0)
{
h.print();
}
//Anything else must be an error.
else
{
cout << endl;
cout << "Error! "<< endl;
}
}while(temp1.compare("quit") != 0);
}
hash.h:
#include <string>
#include <iostream>
#include <cstdlib>
using namespace std;
// Student Class
class Student{
private:
string firstName;
string lastName;
string id;
string year;
string major;
public:
//Constructor
Student(string a, string b, string c, string d, string e);
friend class Element;
friend class Hash;
};
//Element class
class Element{
private:
Student *data;
public:
int getKey();
Student* getData();
void printStudent();
//Constructor
Element(Student *e)
{
data = e;
};
friend class Hash;
};
class Hash{
private:
Element **array;
public:
void add(Element);
void print();
void remove(int);
//Constructor
Hash()
{
array = new Element *[10];
};
friend class Student;
};
hash.cpp:
#include "hash.h"
//The Constructor for Student
Student::Student(string a, string b, string c, string d, string e)
{
firstName = a;
lastName = b;
id = c;
year = d;
major = e;
}
//getKey function for Element Class
int Element::getKey()
{
int key = atoi(getData()->id.c_str());
return key;
}
Student* Element::getData()
{
return data;
}
void Element::printStudent()
{
string c = data->firstName;
cout<< "(" << c << ")";
}
//The add command
void Hash::add(Element e1)
{
int x = e1.getKey()%10;
int i = 0;
if(array[x] == NULL || array[x]->getData() == NULL)
{
array[x] = &e1;
}
else
{while(array[x] != NULL || array[x]->getData() != NULL)
{
x=(x+(i*i))%10;
if(array[x] == NULL || array[x]->getData() == NULL)
{
array[x] = &e1;
break;
}
else
{
i++;
}
}}
}
//The remove command
void Hash::remove(int n)
{
Element e2(NULL);
for(int j = 0; j<10; j++)
{
if(n == array[j]->getKey())
{
array[j] = &e2;
cout << "true" << endl;
break;
}
}
cout << "false" << endl;
}
//The Print command
void Hash::print()
{ int k = 0;
while(k<10)
{
if(array[k] == NULL)
{
cout << "(NULL)";
}
else if(array[k]->getData() == NULL)
{
cout << "(DEL)";
}
else
{
cout << "(" << array[k]->getData()->firstName << ")";
}
k++;
}
cout << endl;
}
Thank you for your help.
You have dangling pointers.
This function gets a temporary copy of an Element, calling it e1.
//The add command
void Hash::add(Element e1)
{
It then stores the address of this local variable.
array[x] = &e1;
And when Hash::add leaves scope, e1 no longer exists.
}
array[x] now points to memory that is no longer Element e1.
The general problem you are facing is that you have designed a Hash class that maintains pointers to objects, but has little control or knowledge regarding when those objects get destroyed.
You will need to personally ensure that objects added to your Hash last at least as long as the Hash does.
Simplest solution for your problem could be to store Element instances in Hash by value not by pointers. So:
class Hash{
private:
Element *array;
public:
void add(Element);
void print();
void remove(int);
//Constructor
Hash()
{
array = new Element[10];
};
friend class Student;
};
Now when you store new element or remove existing you copy them:
array[x] = e1; // not &e1 anymore
This is not very good practice, but at least could change your program in some workable state with minimal changes.

no match for 'operator='

I have built a static stack of structures, and everything works - including creating an array of the structures. However, for some reason I can't set the top of the array to a structure.
In my .cpp file, in my push function, I keep erroring on the following line:
stackArray[top] = newStudent;
The error I am receiving is:
"51: no match for 'operator=' in '(((studentstack)this)->studentstack::stackArray + (+(((unsigned int)((studentstack*)this)->studentstack::top) * 24u))) = ((studentstack*)this)->studentstack::newStudent' "
I am including my code below.
Header file:
#ifndef studentstack_H
#define studentstack_H
#include <iostream>
#include <string>
using namespace std;
class studentstack {
private:
int size; // Stack size
int top; // Top of the Stack
struct student {
int ID;
string Name;
string Address;
double GPA;
};
student * stackArray; // Pointer to the stack
student * newStudent; // Pointer to the new student
public: //Constructor
studentstack(int);
// Copy Constructor
studentstack(const studentstack &);
//Destructor
~studentstack();
//Stack Operaations
void push(string, int, double, string);
void pop(int &);
bool isFull() const;
bool isEmpty() const;
};
#endif
studentstack.cpp
#include <iostream>
#include "studentstack.h"
using namespace std;
studentstack::studentstack(int SIZE) {
stackArray = new student[SIZE];
size = SIZE;
top = -1;
int ID = 0;
double GPA = 0;
}
studentstack::studentstack(const studentstack &obj) {
if (obj.size > 0)
stackArray = new student[obj.size];
else
stackArray = NULL;
size = obj.size;
for (int count = 0; count < size; count++)
stackArray[count] = obj.stackArray[count];
top = obj.top;
}
studentstack::~studentstack() {
delete [] stackArray;
}
void studentstack::push(string name, int id, double gpa, string address) {
if (isFull()) {
cout << "The stack is full.\n";
} else {
top++;
newStudent = new student;
newStudent-> Name = name;
newStudent-> ID = id;
newStudent-> Address = address;
newStudent-> GPA = gpa;
stackArray[top] = newStudent;
}
}
void studentstack::pop(int &id) {
if (isEmpty()) {
cout << "The stack is empty.\n";
} else {
id = stackArray[top].ID;
top--;
}
}
bool studentstack::isFull() const {
bool status;
if (top == size - 1)
status = true;
else
status = false;
return status;
}
bool studentstack::isEmpty() const {
bool status;
if (top == -1)
status = true;
else
status = false;
return status;
}
main.cpp
#include "studentstack.h"
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
int id, var;
string address;
double gpa;
studentstack s[20];
for(int x =0; x<20; x++) {
cout << "New Student Name: " << endl;
cin >> name;
cout << "ID: " << endl;
cin >> id;
cout << "GPA: " << endl;
cin >> gpa;
cout << "Address: " << endl;
cin >> address;
s.push(name, id, gpa, address)
}
cout << "Popping: "
for(int x = 0; x < 5; x++) {
s.pop(var);
cout <<var;
}
return(0);
}
You might want to cut down the example to a minimal piece of code showing the problem. What it comes down to is that you try to assign a student* to a an element in an array of student objects. A pointer to an object is different to an object:
stackArray[0] = new student(); // does NOT work
stackArray[0] = student();
Note, that object are created in C++ by a constructor and not necessarily involving new. When you construct and object using new you still create an object but you also allocate space for it on the heap. By default, objects are created wherever they are defined. For example, student() creates an object on the stack which is then assigned to an object in the memory of stackArray[0].
Not directly related to your question, but note that your main() cannot work. You declare an array of 20 studentstack elements:
studentstack s[20];
and later on you're doing:
s.push(/* ... */);
s.pop(/* ... */);
That doesn't make much sense. s is not a studentstack. It's an array of studentstacks. Arrays in C++ don't have member functions.