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;
}
}
Related
I am trying to do a uni assignment (first year), where the task is to read in a file filled with records (in this case fake student records), insert them into a struct array in the code, write that struct array to a .dat file, and then read the file back in and verify it.
I keep getting an error about converting my struct to a char* (line 155)
Please don't be too technical with the answer, as I have only been coding for a few months ahah
/*
* File: lab3.cpp
* Author: tom
*
* Created on August 19, 2015, 12:02 AM
*/
#include<iostream>
#include<cstring>
#include<fstream>
using namespace std;
//Structure declaration area
struct marks // A structure for user data
{
int studentnumber;
float ass1;
float ass2;
float ass3;
float ass4;
int labs;
float exam;
float total;
};
//Function Prototyping
void structinsert(ifstream&);
void binarywrite(ofstream&);
int binaryread(ifstream& , marks);
//Global Array for student marks
marks students [100];
int main(int argc, char* argv[])
{
ifstream fin;
ofstream fout;
int recordsread = 0;
fin.open(argv[1]); //Input file opened from cmdline args
fout.open(argv[2]); // Output file opened from cmdline args
if (fin.fail())
{
cerr << "Input file not found. Terminating..." << endl;
}
else if (fout.fail())
{
cerr << "Output file not found. Terminating..." << endl;
}
else
{
structinsert(fin);//Function which places data into the global "student" array
binarywrite(fout);
fin.close();
fout.close();
fin.open(argv[2]);
int cnt = 0;
while((!fin.eof()) && (cnt < 100))
{
fin.read(static_cast<char *>(&students[cnt]), sizeof(marks));
cnt++;
}
cout << "Records Read: " << recordsread << endl;
}
return 0;
}
void structinsert(ifstream& input)
{
float temp;
float value;
// Ignore first line of headings
input.ignore(150, '\n');
for (int x = 0; x < 100; x++)
{
input >> students[x].studentnumber;
input.ignore (1);
temp = input.peek();
if (temp == '\t')
{
input.ignore(1,'\t');
students[x].ass1 = 0;
}
else
{
input >> students[x].ass1;
input.ignore(1,'\t');
}
temp = input.peek();
if (temp == '\t')
{
input.ignore(1,'\t');
students[x].ass2 = 0;
}
else
{
input >> students[x].ass2;
input.ignore(1,'\t');
}
temp = input.peek();
if (temp == '\t')
{
input.ignore(1,'\t');
students[x].ass3 = 0;
}
else
{
input >> students[x].ass3;
input.ignore(1,'\t');
}
temp = input.peek();
if (temp == '\t')
{
input.ignore(1,'\t');
students[x].ass4= 0;
}
else
{
input >> students[x].ass4;
input.ignore(1,'\t');
}
input >> students[x].labs;
input.ignore(1,'\t');
temp = input.peek();
if (temp == '\n')
{
input.ignore(1,'\t');
students[x].exam = 0;
}
else
{
input >> students[x].exam;
input.ignore(1,'\t');
}
}
}
void binarywrite(ofstream& output)
{
output.write(reinterpret_cast<char*>(&students),100*sizeof(marks));
}
The class BaseSearch is the base function that I'm trying to call within the derived function (ValueSearch).
The code that I have in question specifically is under ValueSearch, calling BaseSearch::Print(line, title). The compiler errors I'm getting are:
I'm uncertain if I'm using inheritance correctly.
Error 1 error C2275: 'std::string' : illegal use of this type as an expression
BaseSearch.cpp
BaseSearch::BaseSearch()
{
}
BaseSearch::~BaseSearch()
{
}
void Print(string line, string title)
{
char c2 = '_'; //set character to blank value; defines the header row
char c = '_'; //set character to blank value; defines the searched row
int numHeader = 0; //sets the value of character for the header row
int numLine = 0; //sets the value of character for the searched row
c2 = line[numLine];
while (true) //force while loop
{
c = title[numHeader]; numHeader++; //header character is set to the title array defined as the entire header string above
if (c != ',')
{
cout << c; // couts the header until it reaches a ','
}
if (c == ',' || title.size() == numHeader) // if c reaches a ',' it will print the searched row
{
cout << ": ";
while (line.size() != numLine)
{
while (c2 != ',' && line.size() != numLine)
{
cout << line[numLine];
numLine++;
if (line.size() != numLine)
c2 = line[numLine];
else
break;
}
if (line.size() != numLine)
{
numLine++;
c2 = line[numLine];
cout << "\n";
break;
}
}
}
if (title.size() == numHeader) // if c reaches a null value, it breaks until other row is found.
{
cout << endl << endl; break;
}
}
}
BaseSearch.h
#ifndef BASESEARCH_H
#define BASESEARCH_H
#include <string>
class BaseSearch
{
public:
BaseSearch();
virtual ~BaseSearch();
virtual void Print(string, string);
};
Value Search.cpp
ValueSearch::ValueSearch()
{
string input;
}
ValueSearch::~ValueSearch()
{
//dtor
}
double ValueSearch::getInput()
{
cout << endl << "Enter the name of the company you would like to search for: ";
cin >> input;
return input;
}
void ValueSearch::ValueSearchFunc(int c, int x)
{
column = c;
// cout << "Enter the name of the company you would like to search for: ";
// getline(cin, input);
string line;
ifstream fs("Stock Database.csv");
string title;
getline(fs, title);
while (!fs.eof())
{
getline(fs, line);
string companyname = ""; //start as blank, then append
string a;
int commacount = 0; //how many commas have we passed
int ChrCount = 0; //counter for which character in the line we are looking at
while (line != "\0") //while the line does not equal to null value.
{
double price;
price = 0;
a = line[ChrCount]; //convert char c to a string (a) so that we can append
ChrCount++;
if (a == ",")
{
commacount++; //increases the comma count as a encounters a comma each time.
}
else if (commacount == column && (a != "N" && a != "/" && a != "A")) //if comma count is equal to the set column, it will append the string company name.
{
while (a != ",")
{
if (a != ",")
{
companyname.append(a);
a = line[ChrCount];
ChrCount++;
}
}ChrCount--;
price = stod(companyname);
}
else if (commacount > column) // if the comma count is any value larger than the column, breaks out of loop.
{
break;
}
if (input == 0)
{
break;
}
if (x == 1){
if (price >= input && price != 0) // if the appended company name is equal to the search input entered, it will cout the entire row.
BaseSearch::Print(line, title);
}
if (x == 2)
{
if (price <= input && price != 0) // if the appended company name is equal to the search input entered, it will cout the entire row.
BaseSearch::Print(line, title);
}//end if
}
}
}
ValueSearch.h
#ifndef VALUESEARCH_H
#define VALUESEARCH_H
#include <string>
#include "BaseSearch.h"
class ValueSearch : public BaseSearch
{
public:
ValueSearch();
~ValueSearch();
double getInput();
void ValueSearchFunc(int c, int x);
void Print(string,string) {BaseSearch::Print(string,string);}
protected:
private:
double input;
int column;
};
#endif
It seems you are a beginner of C++.I will show you an example code which will compile successfully.
BaseSearc.h:
#ifndef BASESEARCH_H
#define BASESEARCH_H
#include <string>
using namespace std;
class BaseSearch
{
public:
BaseSearch();
~BaseSearch();
void Print(string, string);
};
#endif
BaseSearch.cpp:
#include "BaseSearch.h"
#include <iostream>
BaseSearch::BaseSearch()
{
}
BaseSearch::~BaseSearch()
{
}
void BaseSearch::Print(string line, string title)
{
cout << "line:" << line << endl;
cout << "title:" << title << endl;
}
ValueSearch.h:
#ifndef VALUESEARCH_H
#define VALUESEARCH_H
#include <string>
#include "BaseSearch.h"
class ValueSearch : public BaseSearch
{
public:
ValueSearch();
~ValueSearch();
double getInput();
void ValueSearchFunc(int c, int x);
protected:
private:
double input;
int column;
};
#endif
ValueSearch.cpp:
#include "ValueSearch.h"
ValueSearch::ValueSearch()
{
}
ValueSearch::~ValueSearch()
{
}
double ValueSearch::getInput()
{
return input;
}
void ValueSearch::ValueSearchFunc(int c, int x)
{
//where is 'input' from?
//if (x == 1)
//{
// if (price >= input && price != 0)
// BaseSearch::Print(line, title);
//}
//if (x == 2)
//{
// if (price <= input && price != 0)
// BaseSearch::Print(line, title);
//}//end if
}
But I've no idea what ValueSearchFunc wants to do.
There is no realization of BaseSearch constructor/destructor in code. And Print function realization should be
void BaseSearch::Print(string line, string title)
{
//code
}
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.
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.
I'm quite new to C++, I'm trying to achieve a task whereby i could read from a csv file and write to that same file and vice versa depending on the user's selection. This is what i did:
Here's the data already on file
1,Mickey,23,090,Girne,TRNC,465
2,Charles,23,090,Girne,TRNC,465
3,Species,23,090,Girne,TRNC,465
4,Moody,23,090,Girne,TRNC,465
5,Kpokiyo,23,090,Girne,TRNC,465
6,Sualp,23,090,Girne,TRNC,465
Here's the code i wrote so far
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
bool checkIsFile();
void addUser(string e[][7], int num);
void readAllUsers(string x[][7]);
void breakArray(string x[], string y[][7], int num);
bool checkAccout(string x[], int y, string search);
void findUser(string x[], string y[],string z[], string a[],string t[],
string c[], string d[]);
int findRowNumber();
int main()
{
int option;
int acc;
string emp[findRowNumber()][7];
string account[findRowNumber()], age[findRowNumber()],name[findRowNumber()],
state[findRowNumber()], city[findRowNumber()], phone[findRowNumber()],
zip[findRowNumber()];
//infinite loop
while(true){
cout<<"-------------------------\n";
cout<<"Menu Options\n";
cout<<"1 Add account\n";
cout<<"2 List Accounts\n";
cout<<"3 Delete account\n";
cout<<"4 Find user\n";
cout<<"5 Exit program\n";
cout<<"-------------------------\n";
cin>>option;
if(option==1)
{
readAllUsers(emp);
addUser(emp, findRowNumber());
}
else if(option==2)
{
readAllUsers(emp);
}
else if(option==3)
{
//delete a user;
}
else if(option==4)
{
//find user
readAllUsers(emp);
breakArray(account,emp,0);
breakArray(name,emp,1);
breakArray(age,emp,2);
breakArray(phone,emp,3);
breakArray(city,emp,4);
breakArray(state,emp,5);
breakArray(zip,emp,6);
findUser(account,name,age,phone,city,state,zip);
}
else if(option==5)
{
return 0;
}
else
{
cout<<"Invalid option\n";
}
}
}
void addUser(string e[][7], int num)
{
string emp[num + 1][7];
for(int a=0;a<num;a++)
{
for(int b=0;b<7;b++)
{
emp[a][b] = e[a][b];
}
}
//just to test if it works
emp[num][0] = "10";
emp[num][1] = "10";
emp[num][2] = "10";
emp[num][3] = "10";
emp[num][4] = "10";
emp[num][5] = "10";
emp[num][6] = "10";
ofstream inFile;
inFile.open("info.csv");
for(int a=0;a<num + 1;a++)
{
for(int b=0;b<7;b++)
{
cout<<emp[a][b];
}
}
for(int i=0;i<num +1; i++)
{
inFile << emp[i][0] + "," + emp[i][1] + "," + emp[i][2] + "," + emp[i][3] + "," + emp[i][4] + "," + emp[i][5] + "," + emp[i][6]<<endl;
}
inFile.close();
}
void readAllUsers(string x[][7])
{
ifstream inFile("info.csv");
string line;
int linenum = 0;
while (getline (inFile, line))
{
istringstream linestream(line);
string item;
int itemnum = 0;
while (getline (linestream, item, ','))
{
x[linenum][itemnum] = item;
itemnum++;
}
linenum++;
}
inFile.close();
}
void breakArray(string x[], string y[][7], int num)
{
for(int i=0;i<findRowNumber();i++)
{
for(int j=0;j<7;j++)
{
x[i] = y[i][num];
}
}
}
bool checkAccout(string x[], int y, string search)
{
bool check = false;
for(int i=0;i<y;i++)
{
if(x[i]==search)
{
check = true;
}
}
return check;
}
void findUser(string x[], string y[],string z[], string a[],
string t[], string c[], string d[])
{
string search;
bool check = false;
cout<<"Enter Account Number to Search: ";
cin>>search;
for(int i=0;i<findRowNumber();i++)
{
if(x[i]==search)
{
cout<<"Account Number: " + x[i]<<endl<<
"Name:\t\t" + y[i]<<endl<<
"Age:\t\t" + z[i]<<endl<<
"Phone:\t\t" + a[i]<<endl<<
"City:\t\t" + t[i]<<endl<<
"State:\t\t" + c[i]<<endl<<
"Zip:\t\t" + d[i]<<endl;
check = true;
}
}
if(!check)
cout<<"User does not exist"<<endl;
}
int findRowNumber()
{
ifstream inFile("info.csv");
string line;
int linenum = 0;
while (getline (inFile, line))
{
linenum++;
}
inFile.close();
return linenum;
}
It seems to work great when i choose to search for a user(selecting 4). However, the problem is when i try to write to file, it's works but when i try to do any other task like searching the user again or re-writing to file, the program crashes.
Please what i'm i doing wrong.
Thanks
Your emp string array in the main function is declared with the initial size of the file and never resized when you add more entries, hence the crash when it tries to read a bigger file into the old size of array.