PS Note that std::setfill is sticky, but std::setw isn't.
That is, once you've called setfill the new fill char is used until you call it again to change the char; setw must be called before each insertion you need it for.
Also, the side the field is filled is depends on the alignment. So if you call std::left the fill char will be appended rather than prepended. (There is also std::internal which output e.g. -77 as - 77 if filling with spaces.)
#include <iostream>
#include <iomanip>
#include <string>
int main() {
constint count = 4;
std::cout << std::setfill('0'); // sticky, so need to call once here, rather than in loop
for(int i = 0, ID = 1; i < count; ++i) {
std::cout << "ID = " << std::setw(3) << ID << "\n";
ID *= 7;
}
std::cout << "\n";
std::cout << std::setfill('#') << std::left; // new fill, plus align left
for(int i = 0, ID = 1; i < count; ++i) {
std::cout << "ID= " << std::setw(3) << ID << "\n";
ID *= 7;
}
std::cout << "\n";
std::cout << std::setfill(' ') << std::right; // new fill, plus align right
for(int i = 0, ID = 1; i < count; ++i) {
std::cout << "ID = " << std::setw(3) << ID << "\n";
ID *= 7;
}
std::cout << "\n";
return 0;
}
ID = 001
ID = 007
ID = 049
ID = 343
ID = 1##
ID = 7##
ID = 49#
ID = 343
ID = 1
ID = 7
ID = 49
ID = 343
Actually, setw is the only one of the current set of maniuplators that behaves this way (i.e. is non-sticky.) All the others change the stream's behaviour permanently (well, until the next time they're called) or perform an action (ws, endl, ends, flush.)