I am trying to align the console output in C++ to a decimal point. I have tried the setw, precision options and other flags that aligns to right or left.
But none of those has worked satisfactorily.
The closest option is to use showpos to print (+) sign for positive numbers, but it disturbs the other formatting such as "TE_1_0" to "TE_+1_+0"
1.000000 -0.000000 0.000000
-0.000000 1.000000 0.000000
0.000000 0.000000 1.000000
It will be nice to have it aligned to decimal point to present the output to the people who are interested in. So any help will be much appreciated.
>Solution :
You can do this with a combination of setw, setfill, fixed and setprecesion as follows:
#include <iostream>
#include <vector>
#include <iomanip>
int main()
{
std::vector<std::vector<double>> vec{{10.0233, 122.1, 1203.1},{100.03, 22.15, 3.01},{107.03, 152.1, 0.1},};
for(std::vector<double> tempVec: vec)
{
for(double elem: tempVec)
{
std::cout << std::setw(8) << std::setfill(' ') << std::fixed << std::setprecision(3) << elem << " ";
}
std::cout<< std::endl;
}
return 0;
}
The output of the above is:
10.023 122.100 1203.100
100.030 22.150 3.010
107.030 152.100 0.100
If you modify the above example slightly as shown below:
std::cout << std::setw(12) << std::setfill(' ') << std::fixed << std::setprecision(6) << elem << " ";
Then the output becomes:
10.023300 122.100000 1203.100000
100.030000 22.150000 3.010000
107.030000 152.100000 0.100000
setw is used to set the maximum length of the output, which was 8 and 12 in my given example.
setfill is used to fill the padding places with a char.