The point of this code is to get 15 names and then hash them. After one name is entered I get a segmentation Fault and the program crashes. any help would be appreciated.
Code:
//driver file
#include <iostream>
#include <vector>
#include <string>
using namespace std;
#include "hash.h"
#include "hash.cpp"
int main(void)
{
int a = 0;
hash x;
string name, word2;
cout << "Enter 15 names: " << endl;
while(a <= 14)
{
cin >> name;
x.insert(name);
a++;
}
x.display();
cout << "Enter a word to search for. Enter -999 to quit." << endl;
cin >> word2;
x.search(word2);
return 0;
}
//header file
#include <iostream>
using namespace std;
#ifndef HASH
#define HASH
typedef string hashelement;
class hash
{
public:
hash();
void insert(string word);
void display();
void search(hashelement & word);
private:
vector<hashelement> vec1;
int top;
string word;
};
#endif
//implementation file
#include <iostream>
#include <vector>
#include <string>
#include <cassert>
using namespace std;
#include "hash.h"
hash::hash()
{
vector<hashelement> vec1;
vec1.assign(23, "?");
}
void hash::insert(string word)
{
int stop = 0;
int length = word.length()-1;
int loc = (word[0] + word[length]) % 23;
cout << vec1.size() << endl;
while (stop != 1)
{
if(vec1.at(loc) == "?")
{
vec1[loc] = word;
stop = 1;
}
else
loc++;
}
}
void hash::display()
{
for( int i = 0; i <= 22; i++)
cout << "Postition " << i << "= " << vec1[i] << endl;
}
void hash::search(hashelement & word)
{
int length = word.length()-1;
int loc = (word[0] + word[length]) % 23;
int found = 0;
while( found != 1)
{
if( vec1[loc] == word)
{
cout << word << " Word found at location: " << loc << endl;
found = 1;
}
else if(vec1[loc] == "?")
{
cout << word << " not found" << endl;
found = 1;
}
else
loc++;
}
}