Quote Originally Posted by Angela2010 View Post
There are so many data to be saved ,I want to save them into a txt file. I use the following method:
ofstream out( "zernike.txt ");
out<<"Centroid_x = %6.3f mm\n"<<beam_centroid_x;
the thing is "%6.3f " isn't replaced with the value of beam_centroid_x , "Centroid_x = %6.3f mm\n" is directly printed. is there something wrong with my method,or are there any better methods ? Thank you in advance for your help;
Streams are completely different than printf() or printf()-like functions. The only similarities is that both methods output data.
Code:
ofstream   out( "zernike.txt "); 
out<<"Centroid_x = " << beam_centroid_x << "\n";
Start with that first. Then learn that you have I/O manipulators such as setprecision(), to control how many decimal digits to output. You don't use "6.3f" or anything even remotely similar to that when using streams.

http://www.cplusplus.com/reference/i.../setprecision/
http://www.cplusplus.com/reference/iostream/

Another alternative is to still use CString::Format(), and then just output the entire formatted string at once.
Code:
ofstream   out( "zernike.txt "); 
CString str;
str.Format( "Centroid_x = %6.3f mm\n", beam_centroid_x );
out<< (LPCSTR)str;
Yes, you can use Format() here, but the disadvantage using this (and with any printf()-like functions that have format specifiers) is if you make a mistake matching up the format specifier with the actual type of the variable being outputted, the program will exhibit undesired behaviour (either you get strange output, or the worse case scenario is that your program will crash). For example, you specify "6.3f" and the variable being outputted is a char or some other type that isn't a float.

That's why streams are safer -- you cannot mess up with the format specifier because they do not exist for streams -- you just output the variable and use the manipulators to display the value as desired. But you need to know how to use them (as I've specified above).

Regards,

Paul McKenzie