C++ 使用重载文件读取文件>&燃气轮机;操作人员
我正试图从文件中读取客户的姓名、id和贷款信息。文件的设置如下所示:C++ 使用重载文件读取文件>&燃气轮机;操作人员,c++,operator-overloading,C++,Operator Overloading,我正试图从文件中读取客户的姓名、id和贷款信息。文件的设置如下所示: Williams, Bill 567382910 380.86 Davidson, Chad 435435435 400.00 基本上,每次我使用一个新名称时,信息都会被放入Customer类的一个新对象中。我的问题是,我试图从文件中读取,但我不确定如何正确地重载操作符,以便像我希望的那样从文件中只读取3行,并将它们放在正确的位置 我在此处创建客户并打开文件: Menu::Menu() { Customer C; ifstr
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文件中为菜单类提供的内容。这是我在Customer类的.cpp文件中为重载运算符编写的代码(我知道如何做的一点点)
istream& operator >> (istream& is, const Customer& cust)
{
}
我不确定如何仅获取三条线,并将它们放置在客户内部的相应位置,即:
string name
string id
float loanamount
如果有人能帮我解决这个问题,我将不胜感激。比如:
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;
}
istream&operator>>(istream&is,Customer&cust)//不要让Customer常量,您要写入它!
{
std::getline(is,cust.name);//getline from
是>>客户id;
is>>cust.loanAmount;
is.ignore(1024,“\n”);//读取loanAmount后,跳过尾随的“\n”
回报是;
}
我可以这样写,让getline自动以这种方式获取下一行吗?@cadavid4j:我不知道你的意思?我的文件是按照上面显示的方式设置的,只需说一次getline,转到下一行以输入cust.id和cust.loanamount?这看起来应该可以工作,但是如果成员变量不是
public
,则可能需要将其声明为Customer类的友元。而且,我已经把它当作朋友了。编辑:这个错误现在消失了,我不知道应该从哪里取出常量。在上循环。good()
或上循环。eof()
很少是个好主意。当(myFile>>C){}