ostream operator<<不正常

时间:2015-02-23 19:34:59

标签: c++ arrays printing hashtable ostream

ostream问题 我的ostream运算符<<似乎没有工作或其他什么

1 个答案:

答案 0 :(得分:2)

函数Customer::getHash中存在逻辑错误。这可能无法解决您的问题,但无论如何都应该修复。

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;

}

您可以使用其他变量来保存临时哈希值。

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;    
}

<强>更新

在您发布的代码中,您已在函数

中注释掉了return语句
istream &operator >> (istream &in, Customer &obj)

作为副作用,

的行为
 while (inputFile >> newCustomer)

未定义。

取消注释该行

//return in;

在函数中。这将解决另一个错误。希望这是最后一个。

更新2

您正在while循环中阅读太多信息。

 // 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;
 }

将其更改为:

 while (inputFile >> newCustomer)
 {
    string lastname = newCustomer.getLastname();
    string firstname = newCustomer.getFirstname();
    string id = newCustomer.getID();

    buildCustomerList(cHeadPtr, cTailPtr, lastname, firstname, id);
    customer.insert(newCustomer);
 }
相关问题