ntype
ntype

Reputation: 43

Why does my output go to cout rather than to file?

I am doing some scientific work on a system with a queue. The cout gets output to a log file with name specified with command line options when submitting to the queue. However, I also want a separate output to a file, which I implement like this:

ofstream vout("potential.txt"); ...
vout<<printf("%.3f %.5f\n",Rf*BohrToA,eval(0)*hatocm);

However it gets mixed in with the output going to cout and I only get some cryptic repeating numbers in my potential.txt. Is this a buffer problem? Other instances of outputting to other files work... maybe I should move this one away from an area that is cout heavy?

Upvotes: 4

Views: 293

Answers (3)

Null Set
Null Set

Reputation: 5414

You are getting your C and C++ mixed together.

printf is a function from the c library which prints a formatted string to standard output. ofstream and its << operator are how you print to a file in C++ style.

You have two options here, you can either print it out the C way or the C++ way.

C style:

FILE* vout = fopen("potential.txt", "w");
fprintf(vout, "%.3f %.5f\n",Rf*BohrToA,eval(0)*hatocm);

C++ style:

#include <iomanip>
//...
ofstream vout("potential.txt");
vout << fixed << setprecision(3) << (Rf*BohrToA) << " ";
vout << setprecision(5) << (eval(0)*hatocm) << endl;

Upvotes: 2

Ferruccio
Ferruccio

Reputation: 100658

If this is on a *nix system, you can simply write your program to send its output to stdout and then use a pipe and the tee command to direct the output to one or more files as well. e.g.

$ command parameters | tee outfile

will cause the output of command to be written to outfile as well as the console.

You can also do this on Windows if you have the appropriate tools installed (such as GnuWin32).

Upvotes: 0

BenjaminB
BenjaminB

Reputation: 1849

You are sending the value returned by printf in vout, not the string.

You should simply do:

vout << Rf*BohrToA << " " << eval(0)*hatocm << "\n";

Upvotes: 6

Related Questions