printf("%-8s - %s\n", c->name ? c->name : "", c->help);
I think what you're looking for is
cout << left << setw(8) << (c->name ? c->name : "") << " - " << c->help << endl;
The left
and setw(8)
manipulators together have the same effect as the %-8s
formatting specifier in printf
. You will need to #include <iomanip>
in order for this to work, though, because of the use of setw
.
EDIT: As Matthieu M. pointed out, the above will permanently change cout
so that any padding operations print out left-aligned. Note that this isn't as bad as it might seem; it only applies when you explicitly use setw
to set up some padding. You have a few options for how to deal with this. First, you could just enforce the discipline that before using setw
, you always use either the left
or right
manipulators to left- or right-align the text, respectively. Alternatively, you can use the flags
and setf
function to capture the current state of the flags in cout
:
ios_base::fmtflags currFlags = cout.flags();
cout << left << setw(8) << (c->name ? c->name : "") << " - " << c->help << endl;
cout.setf(currFlags, ios_base::adjustfield);
This works in three steps. The first line reads the current formatting flags from cout
, including how it's currently aligning padded output. The second line actually prints out the value. Finally, the last line resets cout
's output flags for internal alignment to their old value.
Personally, I think the first option is more attractive, but it's definitely good to know that the second one exists since it's technically more correct.
If you've got the Boost libraries:
std::cout << boost::format("%-8s - %s\n") % (c->name ? c->name : "") % c->help;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With