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
  • 37,451
  • 6
  • 88
  • 128
a-z
  • 1,604
  • 3
  • 15
  • 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,251
  • 26
  • 40
  • 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
  • 216,767
  • 17
  • 275
  • 509
1

Yes

 std::right

will right justify and

std::setw(8)

will set the field width to 8.

Grammin
  • 11,224
  • 22
  • 76
  • 135