【问题标题】:Reading from a file using an overloaded >> operator使用重载的 >> 运算符从文件中读取
【发布时间】:2012-09-26 22:33:01
【问题描述】:

我正在尝试从文件中读取客户的姓名、ID 和贷款信息。文件设置如下:

Williams, Bill
567382910
380.86
Davidson, Chad
435435435
400.00

基本上,每次我得到一个新名称时,信息都会被放入 Customer 类的一个新对象中。我的问题是,我正在尝试从文件中读取,但我不确定如何正确重载运算符以像我想要的那样从文件中读取 3 行并将它们放在正确的位置。

我在这里创建客户并打开文件:

Menu::Menu()
{
Customer C;
ifstream myFile;

myFile.open("customer.txt");
while (myFile.good())
{
  myFile >> C;
  custList.insertList(C);
}
}

这正是我在 .cpp 文件中用于 Menu 类的内容。这是我的 Customer 类的 .cpp 文件中重载运算符的代码(我知道怎么做的一点点)。

istream& operator >> (istream& is, const Customer& cust)
{


}

我不确定如何只获取这三行并将它们放置在 Customer 内部的各自位置,它们是:

string name
string id
float loanamount

如果有人能帮我解决这个问题,我将不胜感激。

【问题讨论】:

  • .good().eof() 上循环并不是一个好主意。 See this question. 这样做更简单while (myFile >> C) {}

标签: c++ operator-overloading


【解决方案1】:

类似:

istream& operator >> (istream& is, Customer& cust) // Do not make customer const, you want to write to it!
{
    std::getline(is, cust.name); // getline from <string>
    is >> cust.id;
    is >> cust.loanAmount;
    is.ignore(1024, '\n'); // after reading the loanAmount, skip the trailing '\n'
    return is;
}

And here's a working sample.

【讨论】:

  • 我可以这样写,然后让 getline 自动获取下一行吗?
  • @cadavid4j:我不确定你的意思?
  • 我的文件是按照我上面展示的方式设置的,只是说getline一次,转到下一行输入cust.id和cust.loanamount?
  • 这看起来应该可以工作,但如果成员变量不是 public,您可能需要将其声明为 Customer 类的 friend
  • 当我把它放进去时,我唯一得到的是错误:没有运算符“>>”匹配这些操作数。另外,我已经把它当作朋友了。编辑:这个错误现在消失了,我没有看到我应该在哪里取出 const。
猜你喜欢
  • 2017-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-13
  • 1970-01-01
  • 2015-02-03
  • 2016-04-27
  • 1970-01-01
相关资源
最近更新 更多