-1

I am trying to print all of my output from the console onto a txt file. I know how to do it simply like this:

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

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

But I am trying to do it in this program, since of most of my functions use 'cout', using 'myfile' for each print is very robust. I am trying to it this way, but not sure if it is better to do it as a function:

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;
Mehdi Mostafavi
  • 880
  • 1
  • 12
  • 25
foobar
  • 55
  • 5
  • 6
    Using Linux shell, you can do ./myprogram >> output.txt – Alexandre Senges Mar 18 '20 at 22:27
  • Does this answer your question? [How to redirect cin and cout to files?](https://stackoverflow.com/questions/10150468/how-to-redirect-cin-and-cout-to-files) – rsjaffe Mar 18 '20 at 23:39
  • You state you have a robust way to accomplish your goal. That's good. Why are you not going with it? What's the current problem? – JaMiT Mar 19 '20 at 00:21

2 Answers2

1

Try this:

stream file; 
file.open("cout.txt", ios::out); 
string line; 

// Backup streambuffers of  cout 
streambuf* stream_buffer_cout = cout.rdbuf(); 
streambuf* stream_buffer_cin = cin.rdbuf(); 

// Get the streambuffer of the file 
streambuf* stream_buffer_file = file.rdbuf(); 

// Redirect cout to file 
cout.rdbuf(stream_buffer_file); 

cout << "This line written to file" << endl; 

// Redirect cout back to screen 
cout.rdbuf(stream_buffer_cout); 
cout << "This line is written to screen" << endl; 

file.close();

Source

Shakkozu
  • 40
  • 6
0

Try this:

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

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

  return 0;
}

I understand you want to output content from the console in the file directly, then this would work. Whatever is shown in the console, will be shown in the file. This works fine with the g++ compiler.

Robert Feduș
  • 311
  • 2
  • 16