0

I wanna output a matrix in right-justified fields of length 8 in C++.
Is there any facility to make that easy to code?

Sebastian Mach
  • 38,570
  • 8
  • 95
  • 130
a-z
  • 1,634
  • 4
  • 16
  • 35

3 Answers3

5

You can use std::right and std::setw to get right justified fields in iostream. The default padding char is space, but you can change it with setfill(). Also, right isn't strictly necessary as I believe it is the default, but it's nice to be explicit.

std::cout << std::right << std::setw(8) << data_var
kbyrd
  • 3,321
  • 27
  • 41
  • Please don't encourage the use of `std::endl` when `'\n'` is more appropriate. See [`endl` fiasco](http://stackoverflow.com/questions/5492380/what-is-the-c-iostream-endl-fiasco/5492605#5492605). – Robᵩ Nov 14 '11 at 15:20
1

Perhaps printf("%-8d", 1234); ?

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
1

Yes

 std::right

will right justify and

std::setw(8)

will set the field width to 8.

Grammin
  • 11,808
  • 22
  • 80
  • 138