7

std::coutのコピーをファイルにリダイレクトする必要があります。つまり、出力をコンソールとファイルで確認する必要があります。私がこれを使用する場合:

// redirecting cout's output
#include <iostream>
#include <fstream>
using namespace std;

int main () {
  streambuf *psbuf, *backup;
  ofstream filestr;
  filestr.open ("c:\\temp\\test.txt");

  backup = cout.rdbuf();     // back up cout's streambuf

  psbuf = filestr.rdbuf();   // get file's streambuf
  cout.rdbuf(psbuf);         // assign streambuf to cout

  cout << "This is written to the file";

  cout.rdbuf(backup);        // restore cout's original streambuf

  filestr.close();

  return 0;
}

次に、文字列をファイルに書き込みますが、コンソールには何も表示されません。どうすればいいですか?

4

3 に答える 3

12

最も簡単な方法は、これを行う出力ストリーム クラスを作成することです。

#include <iostream>
#include <fstream>

class my_ostream
{
public:
  my_ostream() : my_fstream("some_file.txt") {}; // check if opening file succeeded!!
  // for regular output of variables and stuff
  template<typename T> my_ostream& operator<<(const T& something)
  {
    std::cout << something;
    my_fstream << something;
    return *this;
  }
  // for manipulators like std::endl
  typedef std::ostream& (*stream_function)(std::ostream&);
  my_ostream& operator<<(stream_function func)
  {
    func(std::cout);
    func(my_fstream);
    return *this;
  }
private:
  std::ofstream my_fstream;
};

このコードの動作については、次の ideone リンクを参照してください

于 2013-01-04T10:55:45.730 に答える
3

を使用することもできますboost::iostreams::tee_device例については、 C++ の「hello world」ブースト ティーのサンプル プログラムを参照してください。

于 2013-01-04T10:56:00.010 に答える
1

streambufストリーム自体ではなく、ストリームに書き込まれた出力の最終的な場所を決定するのは であるため、コードは機能しません。

C++ には、出力を複数の宛先に送信することをサポートするストリームまたはストリームバッファはありませんが、自分で作成することはできます。

于 2013-01-04T10:43:33.960 に答える