2013-10-21 33 views
1

首先,我試圖創建一個文件並寫入它,它不讓我使用「< <」寫入文件,而第二部分我試圖從文件讀取數據,但我不確定這是正確的方式,因爲我想將數據保存到對象中,以便稍後在程序中使用對象。任何幫助或建議非常感謝。在此先感謝如何使用文件I/O C++

void Employee::writeData(ofstream&) 
{ 
    Employee joe(37," ""Joe Brown"," ""123 Main ST"," ""123-6788", 45, 10.00); 
    Employee sam(21,"\nSam Jones", "\n 45 East State", "\n661-9000",30,12.00); 
    Employee mary(15, "\nMary Smith","\n12 High Street","\n401-8900",40, 15.00); 

    ofstream outputStream; 
    outputStream.open("theDatafile.txt"); 
    outputStream << joe << endl << sam << endl << mary << endl; 
    //it says that no operator "<<"matches this operands, operands types are std::ofstream<<employee 
    outputStream.close(); 
    cout<<"The file has been created"<<endl; 
} 

void Employee::readData(ifstream&) 
{ 
    //here im trying to open the file created and read the data from it, but I'm strugguling to figure out how to read the data and save it into de class objects. 
    string joe; 
    string sam; 
    string mary; 

    ifstream inputStream; 
    inputStream.open("theDatafile.txt"); 
    getline(inputStream, joe); 
    getline(inputStream, sam); 
    getline(inputStream, mary); 
    inputStream.close(); 
} 
+3

您需要定義一個'運營商<<'爲'員工'。 – 0x499602D2

+0

@carlpett:'<<'用於輸出,'>>'用於輸入 –

+0

@Ken:哇,我一定累了。沒有更多的SO今晚... – carlpett

回答

3

您收到的錯誤是因爲您需要爲員工類定義輸出運算符。

ostream& operator<<(ostream& _os, const Employee& _e) { 
    //do all the output as necessary: _os << _e.variable; 
} 

它,也能實現輸入操作符是一個好主意:

istream& operator>>(istream& _is, Employee& _e) { 
    //get all the data: _is >> _e.variable; 
} 

你應該讓這些朋友職能類員工:

class Employee { 
    public: 
    //.... 
    friend ostream& operator<<(ostream& _os, const Employee& _e); 
    friend istream& operator>>(istream& _is, Employee& _e); 
    //.... 
} 
+0

@ pipin1289,我試着將操作符添加到我的函數中,現在它說操作符函數的參數太多了。 –

+0

*將它添加到我的課程中... –

+0

@GamalielTellezOrtiz你應該讓它成爲班級的「朋友」功能,並且仍然在外界定義它。 – pippin1289