2012-09-26 102 views
2

我試圖從文件讀取客戶的名稱,標識和貸款信息。該文件是設置這樣的:使用超載>>運算符從文件中讀取

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) 
{ 


} 

我不知道怎麼只得到了三線並將它們放到它們是內部客戶的各自的地方:

​​

如果有人可以幫助我走出這個我」我真的很感激它。

+1

循環上'。好()'或'.EOF()'很少是個好主意。 [見這個問題。](http://stackoverflow.com/questions/4324441/testing-stream-good-or-stream-eof-reads-last-line-twice)只是做'while(myFile >> C){}' – Blastfurnace

+0

感謝此 – cadavid4j

回答

6

喜歡的東西:

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.

+0

我能否像這樣寫,並讓getline自動獲得下一行? – cadavid4j

+0

@ cadavid4j:我不確定你的意思? – Cornstalks

+0

我的文件是按照上面顯示的方式建立的,只會說getline一次,到下一行輸入cust.id和cust.loanamount? – cadavid4j