c++ - 写入文件无法显示所有内容

标签 c++

不知道我在哪里错
我正在尝试用c++写入文件。
这是代码:

struct Student {
   int id;
   std::string name;
    double mark;
   double priority;

   bool operator < (const Student & s) const {
      return (priority < s.priority);
   }
   void print() const {
   std::ofstream myfile;
    myfile.open ("result.txt",std::ios::out);
   myfile << "id: (";
    myfile<< id;
    myfile << ") ";
    myfile<<"name: ";
    myfile<< name;
    myfile << " : ";
    myfile<< " Priority value: ";
    myfile << priority;
    myfile <<"\n";
//  myfile.close();
    std::cout << "name: " << id << ") " << name << " : " << " Priority value: " << priority << std::endl;
   }
};

   void printPriorityQ(std::priority_queue < Student > q) {
      while (!q.empty()) {
         q.top().print();
         q.pop();
      }
      std::cout << std::endl;
   }
我可以成功地将优先级队列的内容输出到控制台,但是正在努力将其输出到result.txt文件
我当前在result.txt中的输出是它打印最后一个项目并停止
例如我的控制台将显示

name: (1) bob: priority value: 5


name: (2) jen: priority value: 4


name: (3) james: priority value: 3


我的txt文件将显示

name: (3) james: priority value: 3


编辑:尝试注释,并将ios::out更改为ios::app我发现它将附加我不想要的文件。
在网上看后,我改用了ios::trunc,但这给了我和以前一样的问题

最佳答案

您当前代码中的问题在于,每次调用print()函数时,该函数都会覆盖输出文件。
不需要您使用ios::app的一种可能的解决方案是如下更改函数的签名:

void print(std::ofstream& myfile ) const {
    myfile << "id: (";
    myfile<< id;
    myfile << ") ";
    myfile<<"name: ";
    myfile<< name;
    myfile << " : ";
    myfile<< " Priority value: ";
    myfile << priority;
    myfile <<"\n";
    std::cout << "name: " << id << ") " << name << " : " << " Priority value: " << priority << std::endl;
   }
并在循环开始之前打开文件,这样该文件只能创建一次:
   void printPriorityQ(std::priority_queue < Student > q) {
      std::ofstream outputFile("result.txt");
      while (!q.empty()) {
         q.top().print(outputFile);
         q.pop();
      }
      std::cout << std::endl;
   }
这应该可以解决您的问题。但是请注意,由于与上述相同的原因,每次调用printPriorityQ时,都会导致文件“result.txt”被覆盖。更好的解决方案也可以使用std::ofstream&引用作为printPriorityQ的输入参数。

关于c++ - 写入文件无法显示所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64662594/

相关文章:

c++ - "strtol"返回不同的值

c++ - 如何使用 VS2015 社区为 C++ 安装 ZeroMQ

c++ - C++ 中的超表示例

c++ - 使用 boost::fusion 迭代时指向类成员的指针

c++ - Linux 中的低级 GPIO 端口(树莓派、香蕉)

c++ - 无法链接我自己的静态库

c++ - 使用 boost spirit 解析为结构

c++ - Codeblocks Windows 和 makefile 生成 C++

c++ - Windows UDP 套接字 : recvfrom() fails with error 10054

c++ - Coderush 不分析 C++ 解决方案