News:

This week IPhone 15 Pro winner is karn
You can be too a winner! Become the top poster of the week and win valuable prizes.  More details are You are not allowed to view links. Register or Login 

Main Menu

C++ Tips: IO - form() equivalents using stream manipulators

Started by ben2ong2, October 06, 2006, 11:24:21 PM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

ben2ong2

(Newsgroups: comp.lang.c++, 9 Dec 97)


BONAKDARIAN: Esmail Bonakdarian

> > Every printf specifier has a corresponding set of ostream specifiers.
> > They're not as compact as in C format strings, but as far as I know
> > they're as comprehensive. The Draft Standard contains a table telling
> > you which iostream specifiers correspond to which C format specifiers.

BECKER: Pete Becker <petebecker@acm.org>

Whoops, I thought there was a table, but it's not there. Bummer.

BONAKDARIAN:

> It's too bad they aren't part of the standard, esp for the basic built
> in types this would be just great. That's all I use them for anyway.
>
> Is there an easy way/wrapper function to format output in C++?
>
> For example if I had this:
>
>       int    i = 12;
>       float  f = 3.14;
>       char   str[20]; // initialized with some string
>
>       cout << form("%3d %03d  %f5.2f  %10s\n", i, i, f, str);

BECKER:

cout << setw(3) << i << ' '
     << setfill('0') << setw(3) << i << setfill(' ') << "  "
     << fixed << setw(5) << setprecision(2) << f << "    "
     << setw(10) << str;

BONAKDARIAN:

>       cout << form("%7d  %f0.2f  %-10s\n", i, f, str);

BECKER:

cout << setw(7) << i << "  "
     << setprecision(2) << f << left << setw(10) << str << '\n';

BONAKDARIAN:

> How would I do this in C++ in the most efficient way?

BECKER:

Not tested, but you get the idea. As I said, not as compact, but just as
powerful, and extensible. You can write your own manipulators to set up
combinations of format specifiers, for example.
You are not allowed to view links. Register or Login
You are not allowed to view links. Register or Login