I wanna output a matrix in right-justified fields of length 8 in C++.
Is there any facility to make that easy to code?
Asked
Active
Viewed 1,924 times
0

Sebastian Mach
- 38,570
- 8
- 95
- 130

a-z
- 1,634
- 4
- 16
- 35
-
don't use the C tag unless you are asking a C question / don't write C/C++ in the title if your question is about C++ – Sebastian Mach Nov 14 '11 at 15:16
-
1in C the answer is : `printf("% 8d", x);` – a-z Nov 14 '11 at 15:16
3 Answers
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
-
-
-
1If the question had been tagged C I would have done +1. But its not. – Martin York Nov 14 '11 at 15:52
1
Yes
std::right
will right justify and
std::setw(8)
will set the field width to 8.

Grammin
- 11,808
- 22
- 80
- 138