2013-11-26 123 views
2

我即將完成我正在編寫的程序,並且已經到了障礙。 我正在試圖打印一個被指針調用的print函數的內容。將功能打印到輸出文件

我的問題是我需要打印輸出文件的功能的內容,我不知道如何。

這是我的打印功能:

void English::Print(){ 

    int formatlength = 38 - (static_cast<int>(firstName.size() + lastName.size())); 

    cout << firstName << " " << lastName; 
    cout << setw(formatlength) << finalExam; 
    cout << setprecision(2) << fixed << setw(11) << FinalGrade(); 
    cout << setw(4) << Lettergrade() << endl; 
} 

這是打印功能的實現:

for (int i = 0; i <= numStudents - 1; i++) { 
    if (list[i]->GetSubject() == "English") { 
     list[i]->Print(); 
    } 
} 

凡for循環是通過我的學生的名單循環。

我的目標是list[i]->Print()將打印到我的輸出文件。

+2

修改函數以將ostream引用作爲參數(可能使用'cout'作爲默認值),並在需要寫入文件而不是'cout'時將相關ostream傳遞給輸出文件。 –

回答

5

只需使用一個ostream對象替換cout,是這樣的:

void English::Print(ostream& fout){ 
    //ofstream of("myfile.txt", std::ios_base::app); 
    int formatlength = 38 - (static_cast<int>(firstName.size() + lastName.size())); 

    fout << firstName << " " << lastName; 
    fout << setw(formatlength) << finalExam; 
    fout << setprecision(2) << fixed << setw(11) << FinalGrade(); 
    fout << setw(4) << Lettergrade() << endl; 
} 

此外,您還可以在你的類English

friend ostream& operator <<(ostream& os, const English& E) 
{ 
    // 
    return os; 
} 

超載<<運營商也然後可以簡單地使用:

fout << list[i] ;

+0

我接受了你的建議,但出現了3個其他問題。這是一個使用派生類的項目,當我爲Print()函數輸入這些參數時,那麼我的子類(英語,數學和歷史)在分配抽象類的對象時都會出錯。 –

0

除了上述問題的答案,我想你應該嘗試這種方式,使用C的原始文件重定向功能:

將該指令放在你的主函數的第一行:

int main(){ 
    freopen("out.txt", "w", stdout); 
    //your codes 

的「出來的。 txt「是要放入數據的文件,」w「表示要在文件中寫入,而stdout是已重定向的標準輸出流。