将函数打印到输出文件

Print function to an output file

本文关键字:输出 文件 打印 函数      更新时间:2023-10-16

我即将完成正在编写的程序,但遇到了障碍。我正在尝试打印一个名为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()将打印到我的输出文件中。

只需将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;
}

此外,您也可以在类English 中重载<<运算符

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

然后可以简单地使用:

fout << list[i] ;

除了上面的答案,我认为你应该尝试这种方法,使用C的原始文件重定向函数:

将此指令放在主函数的第一行:

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

"out.txt"是要将数据放入的文件,"w"表示要在文件中写入,stdout是已重定向的标准输出流。