我即将完成正在编写的程序,但遇到了障碍。 我正在尝试打印由指针调用的名为 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;
}
此外,您还可以重载 <<
运算符也在你的类(class)中 English
friend ostream& operator <<( ostream& os, const English& E )
{
//
return os;
}
然后可以简单地使用:
fout << list[i] ;
关于c++ - 打印函数到输出文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20207560/