Why does my output go to cout and not to a file?

I do scientific work on the queue system. Cout receives the output to the log file with the name specified with the command line parameters when sent to the queue. However, I also want separate output to a file, which I implement as follows:

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

However, it mixes up with the output going to cout, and I only get some mysterious duplicate numbers in my .txt file. Is this a buffer problem? Other instances of output to other files work ... maybe I should move this side away from the area that is heavy?

+4
source share
3 answers

You get mixed C and C ++.

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

Here you have two options, you can print it in the C or C ++ way.

Style C:

 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; 
+2
source

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

You just need to:

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

If it is on a * nix system, you can simply write your program to send your output to stdout, and then use the pipe and tee command to direct the output to one or more files. eg.

 $ command parameters | tee outfile 

will result in the output of the command being written to the outfile, as well as to the console.

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

0
source

Source: https://habr.com/ru/post/1344288/


All Articles