Search code examples
c++coutostreamsetw

C++ setw not aligning columns


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?


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;