On Jun 12, 8:07 am, jacek.dzied...@gmail.com wrote:
Hello!
Can someone tell me what the expected output of the following
program is?
#include <fstream>
#include <iomanip>
using namespace std;
int main() {
ofstream o("o");
o << fixed << setprecision(0) << 13.0 << endl;
}
Depending on which STL implementation I use with my compiler, I
either get
"13" or "13.000000".
I don't have the Standard (at all) or the Josuttis book (with me),
so can anyone
shed some light on what setprecision(0) does? I seem to vaguely
recall that it
turns precision control off (13.000000 would be the 'right' output
then), but I'm
not sure (or is it setprecision(-1)?).
Moreover, I'm after option 1, that is, I insist on printing my
doubles with _no_
digits past the decimal point (and no decimal point), how do I
achieve this
behaviour? The obvious solution "convert to int and output" is not
available to me.
I only have the ofstream object, the output is done by some class's
operator<<,
which outputs a series of doubles and which I cannot modify. Up to
now I could
control everything with setprecision() and a method
set_maths_width() that the
class provides (as setw() works for the first output only), but
when I want a
precision of 0... I'm stumped.
TIA,
- J.
If you know that there will be one decimal place (13.0), rather than
any number, (13.1324), then setprecision(-1) is fine.
Otherwise, you need to round it, floor it, or ceil it. It will remain
a double, but will only have one decimal point (13.1324->13.0).
#include <fstream>
#include <iomanip>
#include <cmath>
using namespace std;
int main(int argc, char *argv[])
{
ofstream o("o");
o << setprecision(-1) << rint(13.150);
return 0;
}
Will get the output you want. If you can't round, but have a lot more
digits, I don't know how to help.
In fact, I tried floor()ing it, but that didn't help.
the irrelevant digits.