将功能打印到输出文件

art*_*lay 2 c++ output

我即将完成我正在编写的程序,并已达成障碍.我正在尝试打印由指针调用的名为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;
}
Run Code Online (Sandbox Code Playgroud)

这是print函数的实现:

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

for循环在我的学生列表中循环.

我的目标是list[i]->Print()将打印到我的输出文件.

P0W*_*P0W 5

只需cout用一个ostream物体替换,例如:

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;
}
Run Code Online (Sandbox Code Playgroud)

此外,您也可以<<在班级中重载操作员English

friend ostream& operator <<( ostream& os, const English& E )
{
  //
  return os;
}
Run Code Online (Sandbox Code Playgroud)

然后可以简单地使用:

fout << list[i] ;