简体   繁体   English

打印功能到输出文件

[英]Print function to an output file

I am about to be finished with a program I am writing and have reached a roadblock. 我即将完成正在编写的程序,并且遇到了障碍。 I am trying to print the contents of a function called print which is called by a pointer. 我正在尝试打印由指针调用的名为print的函数的内容。

My problem is I need to print the contents of the function to an output file and am not sure how. 我的问题是我需要将函数的内容打印到输出文件,并且不确定如何操作。

This is my print function: 这是我的打印功能:

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

This is the implementation of the print function: 这是打印功能的实现:

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

Where the for loop is cycling through my list of Students. for循环遍历我的学生列表。

My goal is that the list[i]->Print() will print to my output file. 我的目标是将list[i]->Print()打印到我的输出文件中。

Simply replace cout with an ostream object, something like : 只需将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;
}

Also, you can overload << operator too in your class English 此外,您还可以重载<<在类运营商太English

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

And then can simply use: 然后可以简单地使用:

fout << list[i] ;

Besides the answers above, I think you should try this way, using the C's original file redirection function: 除了上面的答案,我认为您应该使用C的原始文件重定向功能尝试这种方式:

Put this instruction in the first line of your main function: 将此指令放在主要功能的第一行:

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

The "out.txt" is the file you wanna to put the data in, "w" means you want to write in the file, and stdout is the standard output stream that has been redirected. “ out.txt”是您想要放入数据的文件,“ w”表示您要写入文件,stdout是已重定向的标准输出流。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM