C ++打印控制台输出到txt文件?

时间:2020-03-18 22:24:35

标签: c++ file

我正在尝试将控制台的所有输出打印到txt文件中。我知道如何做到这一点:

int main()
{
    ofstream outfile;
    outfile.open("Text.txt");

    outfile << "Hello World!\n";
    outfile.close();
}

但是我正在尝试在此程序中执行此操作,因为我的大多数功能都使用'cout',因此对于每个打印使用'myfile'是非常可靠的。我正在尝试通过这种方式,但是不确定是否最好将其作为函数来实现:

int main()
{
    string st;
    ofstream myfile;
    myfile.open("Game.txt");
    myfile << st;

        Player P1("player 1 ", true);

        Player P2("Computer", false);
        Board myboard(1);


            int cardno;
            int pos;

                cout << "\n\n\n               Please select a position on Board: ";

        getch();
        myfile.close();
        cout << st;
    return 1;

2 个答案:

答案 0 :(得分:1)

尝试一下:

CMD apachectl -D FOREGROUND

enter image description here

答案 1 :(得分:0)

尝试一下:

using namespace std;
ofstream output("myfile.txt");

int main()
{
  cout << "Content to display on console";
  output << "Content to display in file";

  return 0;
}

我了解您想直接从控制台在文件中输出内容,这样就可以了。控制台中显示的内容将显示在文件中。在g ++编译器上可以很好地工作。