How Can I Align Columns Neatly in C++ Output?

  • Thread starter Thread starter FrostScYthe
  • Start date Start date
  • Tags Tags
    Columns
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
3 replies · 3K views
FrostScYthe
Messages
80
Reaction score
0
Hey after I run my program in C++ I get my results this way with this line of code:

count << setprecision(7) << fa << '\t' << fm << '\t' << fabs(b-a);

f(a) f(m) error
-308 154.375 4.5
-308 25.70313 2.25
-308 -111.248 1.125
-111.248 -35.8313 0.5625
-35.8313 -3.395538 0.28125
-3.395538 11.56259 0.140625
-3.395538 4.186766 0.0703125
-3.395538 0.4215546 0.03515625

I want to make it tidier, and for the columns to be straight, anyone know how to do that easily?
 
Physics news on Phys.org
Damn you can't notice it her, but anyway I mean the spaces between the numbers are uneven, if you get what I mean.
 
C# has the methods String.PadLeft(size, char), String.PadRight(size, char) which adds a number of characters to the left, or right, of the string so that the final length will be the specified size.
Doing your own padding function is simple. In pseudo code:

function PadRight(string str, int size, char c){
int diff = size - str.Length;
for(int i=0; i<diff; i++){
str.append(c);
}
return str;
}

Then you Pad your numbers before outputting them.
In C, with printf, you can specify flags that do this automatically, I'm not sure in C++, I'm not very rotated in that language.
This should probably be better off int he programming forum.
 
Last edited:
Use [ code ] ... [ /code ] tags for text you want to appear verbatim:

Code:
f(a)    f(m)    error
-308    154.375 4.5
-308    25.70313        2.25
-308    -111.248        1.125
-111.248        -35.8313        0.5625
-35.8313        -3.395538       0.28125
-3.395538       11.56259        0.140625
-3.395538       4.186766        0.0703125
-3.395538       0.4215546       0.03515625

Anyways, why not use the setw manipulator? (And use left and right if you want to control the justification)