【问题标题】:ostream operator<< not working properlyostream 运算符<< 无法正常工作
【发布时间】:2015-04-25 06:07:52
【问题描述】:

ostream 问题 我的 ostream 运算符

【问题讨论】:

  • 嗯,我想 (int)key[i] 会因为大小不匹配而给你垃圾数据......
  • 我的大小是 512,进入 getHash 的大小是 512。你有什么建议?谢谢

标签: c++ arrays printing hashtable ostream


【解决方案1】:

函数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 循环是否正常工作?在我看来,这里有一些非常简单的东西,但我无法抓住它!谢谢
  • @kris,for 循环对我来说看起来不错。
  • @R Sahu,我发布了我的完整程序。我在想,也许当我在读取文件和设置数据时,出了什么问题?
  • 任何帮助将不胜感激,我在这个问题上花了大约 3 天的时间,我想我差不多完成了
  • @R Sahu,感谢您的帮助。这并没有解决我的问题,但这是其中的一部分。谢谢!我想我的设置和插入功能搞砸了,因为只打印了一条记录而不是 512
猜你喜欢
  • 2015-11-27
  • 1970-01-01
  • 2021-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多