Hi I got a little question here.
I am doing my C++ homework and the sample output is
% cat this.out
5.00 0.00
1.55 4.76
-4.05 2.94
-4.05 -2.94
1.55 -4.76
but what I got was
% cat test.out
5 0
1.55 4.76
-4.05 2.94
-4.05 -2.94
1.55 -4.76
And I couldn't figure out how to make my output format looks like that.
One more problem I had in this case is, I want the first line in my output is something like 5.00 0.00, but it doesn't work even I set precision(3)
Here is my code generates the output, please take a look.
file.open (filename, fstream :: in | fstream :: trunc);
if(!file.is_open())
{
cerr << "Error opening file " << filename << endl;
cout << "Exiting..." << endl;
exit(0);
}
for(i = 0 ; i < num; i ++)
{
angle = 2 * M_PI * i/num;
x = rad * cos(angle);
y = rad * sin(angle);
file.precision(3);
// x, y are double
file << "\t" << x << "\t" << y << endl;
}
cout << "finished";
file.close();
You need to look up the Input/output manipulators in the Standard library header <iomanip>.
These are used inline, like:
std::cout << "\t" << std::fixed << std::setprecision(z) << x
The ones you'll be most interested in are:
std::fixedstd::setprecisionstd::setwThis should do the trick:
file.precision(2);
file << fixed << "\t" << x << "\t" << y << endl;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With