#include <iostream>
using namespace std;
int main()
{
cout << -0.152454345 << " " << -0.7545 << endl;
cout << 0.15243 << " " << 0.9154878774 << endl;
}
Outputs:
-0.152454 -0.7545
0.15243 0.915488
I want the output to look like this:
-0.152454 -0.754500
0.152430 0.915488
My solution:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout << fixed << setprecision(6) << setw(9) << setfill(' ') << -0.152454345 << " ";
cout << fixed << setprecision(6) << setw(9) << setfill(' ') << -0.7545 << endl;
cout << fixed << setprecision(6) << setw(9) << setfill(' ') << 0.15243 << " ";
cout << fixed << setprecision(6) << setw(9) << setfill(' ') << 0.9154878774 << endl;
}
The output is good, but the code is terrible. What can be done? Here is my code https://ideone.com/6MKd31
Specifying an output format is always terrible. Anyway you can just omit to repeat stream modifiers that are conserved across input/output and repeat only those that are transients (setw
):
// change state of the stream
cout << fixed << setprecision(6) << setfill(' ');
// output data
cout << setw(9) << -0.152454345 << " ";
cout << setw(9) << -0.7545 << endl;
cout << setw(9) << 0.15243 << " ";
cout << setw(9) << 0.9154878774 << endl;
This might not quite be what you want, but I thought I'd throw it out there anyway as it's very simple.
If you can tolerate a leading +
for non-negative numbers then you can use
std::cout << std::showpos << /*ToDo - the rest of your output here*/
At least then everything lines up, with minimal effort.
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