Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert this C line to C++? using cout command

Tags:

c++

c

printf("%-8s - %s\n", c->name ? c->name : "", c->help);
like image 583
Valentina Rose Avatar asked Feb 11 '11 07:02

Valentina Rose


2 Answers

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.

like image 122
templatetypedef Avatar answered Oct 24 '22 07:10

templatetypedef


If you've got the Boost libraries:

std::cout << boost::format("%-8s - %s\n") % (c->name ? c->name : "") % c->help;
like image 33
Fred Foo Avatar answered Oct 24 '22 09:10

Fred Foo