Question

I've got an ostream called os that I use like this:

os << rec.lastname << " " << rec.firstname << setw(30) << rec.phonenum;

And the output is showing up like this:

WITT CANDACE                  250-939-5404
PERKINS THEODORE                  723-668-3397
HULL THAD                  708-807-6757
SALAZAR STEPHAN                  415-413-5058
WILKINS ISRAEL                  938-701-1455
PERRY BRUCE                  540-916-2956
RIVERS VALENTIN                  726-204-2377
JOHNSTON WILFRED                  582-126-8861
SPENCE LEVI                  985-365-7415
NGUYEN KAYLA                  484-322-1527

I know this has been asked many times before, but the answer is always to use setw(), which isn't working in my case. Any ideas why?

Was it helpful?

Solution

setw will add the number of spaces to the output stream. If you want to line up colums, you'll need to subract the size of previous stings:

os << rec.lastname << " " << rec.firstname << setw(30 - rec.lastname.size() - rec.firstname.size()) << rec.phonenum;

OTHER TIPS

<< setw( 30 - rec.lastname.size() - rec.firstname.size() )

Will work until the size of firstname and lastname will be < 30. Then setw will receive negative value and will output the text just after the lastname

You can evaluate the maximum length of record values, add some spaces and use this value for alignment:

<< setw( start2ndColumnPosition - rec.lastname.size() - rec.firstname.size() ); 

But, if you are sure in your data you can leave 30.

BTW: right adjustment is set by default

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top