How to output to a file

Hi: Thanks to all who read and help :)

I have an algorithm that is churning out a bunch of factors that I need to manage. Currently it is a simple cout that when running merely scrolls on the console page. Obviously it is impossible to capture the numbers because of the scroll. So I would like to have a more manageable output.

The code looks like this:

if (fabs(firstX - secondX) < fabs(0.05 * firstX) && fabs(firstY - secondY) < fabs(0.05 * firstY)) {
cout << firstX << " / " << firstY << endl;
cout << "X factors: " << array1[x1] << " " << array1[x2] << endl;
cout << "Y factors: " << array2[y1] << " " << array2[y2] << endl;



If this could be outputted to a file that I could open that would satisfactory. Could that be Notepad or could a spreadsheet like Excel or Microsoft Works Spreadsheet be used?

Or could the console window just hold the values such as in a table? Could you sort the information based upon the numerical value?

Currently the output (format) looks like:

937 / 785
X factors: 3.04, 0.43
Y factors: 0.32, 3.04

Thanks again!
There are two ways.

1. If you're running the program from the command line, simply redirect the output to a pager or a file.
e.g.
yourapp | less
or
yourapp > out.txt

2. You can write directly to a file yourself. You need to create file and write to the file instead of cout.

At the top of your program add:
1
2
#include <fstream>
std::ofstream fileout("out.txt");

Then replace cout with fileout within your program.

You won't see anything on the screen, output will go to file out.txt.
Last edited on
1. If you're running the program from the command line, simply redirect the output to a pager or a file.
e.g.
yourapp | less
or
yourapp > out.txt

Didn't know that.
Is it a stream rebind?
It's called redirection.

Unix consoles have 3 streams, stdin, stdout and stderr, in C++ these map onto cin, cout and cerr respectively. These can all be redirected at the console.

The main reason for this is to chain programs together to do the job of a larger custom app. For example, if you wanted to sort your output, you'd redirect it into sort.
e.g.
yourapp | sort

Or if you wanted to see the output as it went past, but only lines starting with error
yourapp | tail -f | grep '^error'
Interesting.
And windows console?
I'm pretty sure windows supports the > syntax, not sure about the | though.
Microsoft's console has been incrementally improved over the decades and can even seperate stdout from stderr. But you won't have the Unix or GNU tools available. There's sort and more but not much else.

The early GNU tools were compiled as native win32 apps, these days no one bothers. Cygwin or MKS Toolkit or some other Unix-like environment tends to be used.
Topic archived. No new replies allowed.