Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ cout aligning output numbers

#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

like image 303
ancajic Avatar asked Dec 18 '22 00:12

ancajic


2 Answers

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;
like image 112
Jean-Baptiste Yunès Avatar answered Dec 24 '22 00:12

Jean-Baptiste Yunès


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.

like image 33
Bathsheba Avatar answered Dec 24 '22 01:12

Bathsheba