0

I'm trying to hash the contents of a file line by line. The procedure i have thought was to get the last character of the string and then hash that last character but it,s giving me problems. any help would be appreciated.

int HashTable::hashFunction(string key) {
    char last = key[14]; //--->>!!!! the problem happens here where an out of range error pops up 
                                  ///although the string passed is 16 characters long
    int ila = int(last) - 48;  //CONVERT LAST CHARACTER TO INTEGER
    return  ila % hashGroups;
} 


void HashTable::read_from_file() {
    fstream myfile;
    string input, pass, account number;
    myfile.open(address1.c_str(), ios::in);
    while (!(myfile.eof())) {
        getline(myfile, account number, ',');
        getline(myfile, pass, '\n');
        int hashValue = hashFunction(account number);
    }
    myfile.close();
}
Paul Sanders
  • 15,937
  • 4
  • 18
  • 36
  • So it's not 16 chars long. – Igor R. May 09 '20 at 10:27
  • After affirming the string is not empty, you could just use `char last = key.back();` . And fyi, this code is broken regardless. See [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) You're not checking (a) for file-open success, nor (b) *any* of the actual IO operations success. – WhozCraig May 09 '20 at 10:27
  • Thanks man @WhozCraig.That helped me solve the issue – Soheil_mtr May 09 '20 at 11:32
  • This is a code I came up with. It works without issues. For sure it can be improved but i think it's a good starting point for beginners like myself.Hope it helps. – Soheil_mtr May 20 '20 at 12:02

0 Answers0