c++ - 打印函数到输出文件

标签 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;
}

这是打印功能的实现:

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

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

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

最佳答案

只需替换 coutostream对象,例如:

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;
}

此外,您还可以重载 <<运算符也在你的类(class)中 English

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

然后可以简单地使用:

fout << list[i] ;

关于c++ - 打印函数到输出文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20207560/

相关文章:

c++ - "a struct has public inheritance by default"

c++ - 没有初始值设定项或显式默认构造函数的空类是否可用作 constexpr 变量?

c++ - 如何在 Ubuntu 中将 Qt 源添加到 QtCreator?

c++ - 模块化游戏引擎 : DLL circular dependencies

output - Stata 表 : Using esttab, 用 xtreg 表示()

css - 如何使 HTML5 输出使用逗号?

c++ - 我正在尝试用 vector 拍摄

c - 素数输出错误

c - 为什么在第一个代码中更改了实际参数?

java - 用 Java 将程序输出写入文件(并再次读取)