Question

I know that in C++ I can use setprecision as follows:

streamsize prec = cout.precision();

cout << "Your grade is: " << setprecision(3) << finalGrade << setprecision(prec);

How can I adapt this to the following old style code, particularly when writing to a file?

for ( int k = 0 ; k < vector.size() ; k++ )
{
   fprintf( myFile, "%i\t%f\t%f\n", k+1, vector[k].x, vector[k].y );

   std::cout << vector[k].x << "\t" << vector[k].y;
}

What specifically I am confused about is the order in which setprecision(3) and setprecision(prec) appear, when there is more than one variable, like in the case of vector elements being written to a file...

Could somebody please help me understand this?

Thank you,

Was it helpful?

Solution

It was not clear from the question that you want the setprecision to modify how fprintf works; it's only clear from the comments.

This is impossible (at least, with the existing C++ standard library).

The stdio and iostreams systems are separate, mostly independent parts in C++. In addition, the iostreams stuff was standardized after the stdio stuff, so to support having setprecision affect fprintf would mean changing fprintf code, which no one wants to do.

To give an idea on how separate they are, look at ios_base::sync_with_stdio - a dedicated function to make fpritnf and operator<< interoperate.

To make your system work, you probably have to replace fprintf by operator<<. Another way would be adjusting the fprintf's format string, but you would have to add the obscure call to ios_base::sync_with_stdio to your code.

OTHER TIPS

The way to indicate the number of decimals in fprintf is %.[number]f; in your case, for 3 decimals the code will be

fprintf( myFile, "%i\t%.3f\t%.3f\n", k+1, vector[k].x, vector[k].y );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top