将函数打印到输出文件
Print function to an output file
我即将完成正在编写的程序,但遇到了障碍。我正在尝试打印一个名为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是已重定向的标准输出流。
相关文章:
- 有没有办法简单地从 GPU 调用多个 cpp 输出文件?
- VI工作室代码错误无法打开输出文件主.exe
- 在代码块中查找输出文件
- 将未签名的字符写入输出文件
- 为什么我的代码不写入输出文件?
- 完成搜索任务时为空输出文件
- 如何将地图<列表<string>、矢量<string>>输出到输出文件?
- 无法在代码块 IDE 中打开输出文件.exe
- C++:更改 IF 语句中的输出文件
- 编译 gsoap 输出文件 (onvif) 时出现问题
- C++击球平均值程序使用输入/输出文件打印名称,平均值,最高/最低平均值时遇到麻烦
- while 循环中的流输出文件() 通常生成空文件
- 如何使用 Docker 访问输出文件
- 提升进程间共享内存删除、权限和输出文件
- 查找素数,然后将质数放入输出文件中
- GDB / C++ - 根据循环条件将多个变量记录到输出文件中
- 带有文件结束函数的 while 循环重复输出文件中的最后一个数字两次
- 我的输出文件未显示解决方案
- 输入文件中的第一个字符是输出文件中的最后一个字符,反之亦然
- C++,我正在尝试创建一个有效的.bmp输出文件