Search code examples
c++arraysprintinghashtableostream

ostream operator<< not working properly


ostream issues My ostream operator << seems not to be working or something else


Solution

  • There is a logic error in the function Customer::getHash. That may not solve your problem but it should be fixed anyway.

    int Customer::getHash(int hash)
    {
        string key = getLastname();
        cout<<"key: "<<key<<endl;
        // getFirstname();
        //  getID();
        int i = 0;
        // int j = 0;
        // int k = 0;
        for (i = 0; i < key.length(); i++)
        {
            i += (int)key[i]; // Problem.
                              // At this time, i may be greater than key.length().
        }
       // getFirstname();
       // getID();
       return  i = i % hash;
    
    }
    

    You can fix it by using a different variable to keep the temporary hash value.

    int Customer::getHash(int hash)
    {
        string key = getLastname();
        cout<<"key: "<<key<<endl;
        int tempHash = 0;
        int i = 0;
        for (i = 0; i < key.length(); i++)
        {
            tempHash += (int)key[i];
        }
       return  tempHash % hash;    
    }
    

    Update

    In your posted code, you have commented out the return statement in the function

    istream &operator >> (istream &in, Customer &obj)
    

    As a side effect, the behavior of

     while (inputFile >> newCustomer)
    

    is undefined.

    Uncomment the line

    //return in;
    

    in the function. That will fix another error. Hopefully that's the last one.

    Update 2

    You are reading too much information in the while loop.

     // This line reads all the information of one customer
     while (inputFile >> newCustomer)
     {
        //inputFile >> newCustomer;
        string lastname;
    
        // PROBLEM
        // Now you are reading data corresponding to the next customer.
    
        getline (inputFile, lastname, ' ');
        while (inputFile.peek() == ' ')
           inputFile.get();
    
        string firstname;
        getline (inputFile, firstname, ' ');
        while (inputFile.peek() == ' ')
           inputFile.get();
    
        string id;
        getline (inputFile, id);
    
        buildCustomerList(cHeadPtr, cTailPtr, lastname, firstname, id);
        customer.insert(newCustomer);
        //cout<<lastname<<endl;
        //cout<<firstname<<endl;
        //cout<<id<<endl;
     }
    

    Change it to:

     while (inputFile >> newCustomer)
     {
        string lastname = newCustomer.getLastname();
        string firstname = newCustomer.getFirstname();
        string id = newCustomer.getID();
    
        buildCustomerList(cHeadPtr, cTailPtr, lastname, firstname, id);
        customer.insert(newCustomer);
     }