使用重载的>>从文件中读取操作者

时间:2012-09-26 22:33:02

标签: c++ operator-overloading

我正在尝试从文件中读取客户的姓名,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类。以下是我的.cpp文件中Customer类的重载运算符的代码(我知道该怎么做)。

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


}

我不确定如何只获得三条线并将它们放入客户内部各自的位置:

string name
string id
float loanamount

如果有人能帮助我,我真的很感激。

1 个答案:

答案 0 :(得分:7)

类似的东西:

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.

相关问题