Is there an easier way to get everything into an output file?

For example, rather than echoing each 'cout' statement in my entire program with an 'outfile' statement, is there an easier way to do it? Maybe some awesome code up at the top somewhere that means the same thing? I just want to copy whatever shows on my output screen when I run the program, and save it to a file.

Anyone? I'm SO hoping for a yes!
Thanks!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<fstream>

using namespace std;

int main()
{

  ofstream output("output.txt");

  for(int i=0; i<5; i++)
  {
      output<<i<<endl;
   }
   return 1;

}
Well, I already know that one. I mean different than that. But thanks for trying.
Something that isn't coded in, exactly, just maybe one statement up at the top that would copy the entire program's output screen to a file?

Does that exist?
what you compile and run

 
./a.out >>output.txt
You can use operator overloading for ostream.
Cout and ofstream are both ostream objects. Meaning you can write one function and it can work with both:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <fstream>
using namespace std;

void print(const char name[], const int& age, const int weight, ostream& out = cout);

int main(void)
{
  ofstream outFile;
  const int SIZE = 128;
  int age, weight;
  char name[SIZE];

  cout << "Please enter your name: ";
  cin.getline(name, SIZE);
  cout << "Enter your age: ";
  cin >> age;  cin.ignore(80, '\n');
  cout << "Enter your weight: ";
  cin >> weight;  cin.ignore(80, '\n');
  
  print(name, age, weight);
 
  outFile.open("output.txt");
  if (outFile.is_open())
  {
    print(name, age, weight, outFile);
    outFile.close();
  }
  else
    cout << "Couldn't open \"output.txt\"\n";
  
  cout << "\n\nAll done, hit enter to quit.";
  cin.get();
  return 0;
}

void print(const char name[], const int& age, const int weight, ostream& out)
{
  if (out == cout)
    out << endl;

  out << "Your name is " << name << endl
      << "You are " << age << " years old" << endl
      << "You weight " << weight << " tons.";
}





Last edited on
Topic archived. No new replies allowed.