首页 > 解决方案 > C ++如何将输出保存到文件中

问题描述

所以我不确定如何让输出像 .txt 文件一样,代码一直给我一个 .txt 文件,但它总是空的。我知道我应该在其中包含输出信息的行,但我不确定要在该行中放入什么,因为它是一个 void 函数并且它不返回任何内容,将其更改为不同类型的函数会解决问题?

代码:

#include <iostream>
#include <string>
#include <fstream>
#include "ArgumentManager.h"

using namespace std;

void permute(string a, int l, int r)
{
  if (l == r)
    cout<<a<<endl;
  else
  {
    for (int i = l; i <= r; i++)
    {
      swap(a[l], a[i]);
      permute(a, l+1, r);
      swap(a[l], a[i]);
    }
  }
}

int main(int argc, char* argv[])
{
  ArgumentManager am(argc, argv);
  ifstream input;
  ofstream output;

  string infileName = am.get("input");
  string outfileName = am.get("output");
  input.open(infileName);
  output.open(outfileName);

  string str;

  int n = str.size();
  permute(str, 0, n-1);

  return 0;
}

标签: c++c++11

解决方案


我以前没有在 C++ 中使用过 ArgumentManager。但是你可以使用类似的东西:

// basic file operations
#include <iostream>
#include <fstream>
using namespace std;

int main () {
  ofstream myfile;
  myfile.open ("example.txt");
  myfile << "Writing this to a file.\n";
  myfile.close();
  return 0;
}

我认为与其将输出传递给 cout,不如将其传递给 myfile 对象。


推荐阅读