【发布时间】:2015-04-25 06:07:52
【问题描述】:
ostream 问题 我的 ostream 运算符
【问题讨论】:
-
嗯,我想 (int)key[i] 会因为大小不匹配而给你垃圾数据......
-
我的大小是 512,进入 getHash 的大小是 512。你有什么建议?谢谢
标签: c++ arrays printing hashtable ostream
ostream 问题 我的 ostream 运算符
【问题讨论】:
标签: c++ arrays printing hashtable ostream
函数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);
}
【讨论】:
for 循环对我来说看起来不错。