I'm accepting an input file with names in it. It looks like:
I'm trying to put the names into a hash table. Here is my code:
Code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int hash(char *str, int table_size);
int main(int argc, char* argv[])
{
string array1[12];
char name[20];
ifstream inFile ( argv[1] );
if ( !inFile.is_open() )
{
cout << "Could not open file." << endl;
}
else
{
inFile.get(name, 20) >> array1[hash(name, 12)];
for(int i = 0; i < 12 ; i++)
{
cout << endl;
cout << i << ": " << array1[i];
cout << endl;
}
}
cin.get();
return 0;
}
int hash(char *str, int table_size)
{
int sum = 0;
/* Make sure a valid string passed in */
if (str == NULL)
{
return -1;
}
/* Sum up all the characters in the string */
for( ; *str; str++)
{
sum += *str;
}
/* Return the sum mod the table size */
return sum % table_size;
}
The program compiles fine. But, when i run it (using windows command prompt) it crashes.
I think the problem is how i'm declaring name:
and how it is being used with the hash function:
I can't figure out how to fix this.
I also have two other smaller issues.
1) When i read the names in from the file, it skips the first name.
Code:
inFile.get(name, 20) >> array1[0];
This will read Sparks into the first position instead of Steve.
2) The names aren't being hashed in the same spot that the example from this site gives:
http://www.sparknotes.com/cs/searchi.../section1.html
Any help would be appreciated.