name ? c->name : "", c->help); +7 c ++ c Valentina rose Feb 1...">

How to convert this C string to C ++? using cout command

printf("%-8s - %s\n", c->name ? c->name : "", c->help); 
+7
source share
2 answers

I think you are looking

 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 format %-8s in printf . You will need #include <iomanip> for this to work, however, due to the use of setw .

EDIT . As Mattiu M. noted, the above constantly changes cout so that any fill operations are displayed to the left. Please note that this is not as bad as it might seem; this only applies when you explicitly use setw to configure some add-on. You have several options for dealing with this. First, you can simply enforce the discipline that before using setw you always use either the left or right manipulators to align the text left or right, respectively. Alternatively, you can use the flags and setf functions 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 currently aligns the output. The second line actually prints the value. Finally, the last line resets the cout output flags for internal alignment to its old value.

Personally, I think that the first option is more attractive, but he definitely knows that the second exists, because it is technically more correct.

+12
source

If you have Boost libraries:

 std::cout << boost::format("%-8s - %s\n") % (c->name ? c->name : "") % c->help; 
+9
source

All Articles