i got this problem in creating a hash table for string. Basically, my program will ask the user to input the string, than the program will create the index by calculating the ascii number of the string and put the string into an array of pointers. and i also use struct to contain the string. this is my code ( its a english-indonesia dictionary) :
Code:
#include <iostream>
#include <string>
using namespace std;
struct EnglishIndonesia{
string english;
string indonesia;
EnglishIndonesia *link;
};
EnglishIndonesia *p, *newNode;
EnglishIndonesia *q[99];
void mainMenu();
void addDef();
void searchDef();
void deleteDef();
int quit();
int hashing (string s);
void show (EnglishIndonesia x[]);
void createNode(string a, string b);
int main (int argc, char * const argv[]) {
mainMenu();
}
void mainMenu()
{
int choice;
cout<<"Welcome to Dictionary of English-Indonesia 2012(KIAMAT !)"<<endl;
cout<<"What do You want to do ?"<<endl;
cout<<"1. add Definition to Dictionary"<<endl;
cout<<"2. Search for Definition"<<endl;
cout<<"3. delete Definition"<<endl;
cout<<"4. Quit"<<endl;
cout<<"Enter the number you want : ";
cin>>choice;
if( choice == 1)
{
addDef();
}
else if (choice == 2)
{
searchDef();
}
else if (choice == 3)
{
deleteDef();
}
else if ( choice == 4 )
{
quit ();
}
else
{
cout<<"Input Invalid ! Enter between 1-4 !"<<endl<<endl;
mainMenu();
}
}
void addDef()
{
int no;
int hashVal;
string a;
string b;
while ( no != 2)
{
cout << "Word in English : ";
cin>> a;
cout<<"Transelation in Indonesia : ";
cin>> b;
createNode(a,b);
hashVal = hashing (newNode->english);
q[hashVal] = newNode;
cout<<"Do You Want To Continue ? ( 1.Yes 2.No) ";
cin>>no;
}
}
void searchDef()
{
}
void deleteDef()
{
}
int hashing ( string s )
{
int total = 0;
int k = 0;
int i = 0;
char z[99];
while (k < 99)
{
z[k] = s.at(k);
k++;
}
while(i < 99)
{
total = total + (int)z[i];
i++;
}
return total % 99;
}
void show (EnglishIndonesia x[])
{
for ( int i = 0; i <= 99; i++)
{
if(q[i] != NULL)
{
cout<<q[i]->english<<endl;
cout<<q[i]->indonesia<<endl;
}
}
}
int quit()
{
return 0;
}
void createNode ( string a, string b)
{
newNode = (EnglishIndonesia *)malloc(sizeof(EnglishIndonesia));
if (newNode != NULL)
{
newNode->english = a;
newNode->indonesia = b;
}
else
cout <<"Memory FULL !";
}
i have no idea where i'm doing wrong. i mean the program just crash after the second input.