Path: utzoo!utgpu!jarvis.csri.toronto.edu!rutgers!tut.cis.ohio-state.edu!gem.mps.ohio-state.edu!rpi!uwm.edu!lll-winken!ubvax!ardent!jra!jss From: jss@jra.ardent.com (Jerry Schwarz (Compiler)) Newsgroups: comp.lang.c++ Subject: Re: Formatted Output Revisited Message-ID: <8783@ardent.UUCP> Date: 23 Oct 89 23:23:23 GMT References: Sender: news@ardent.UUCP Reply-To: jss@jra.ardent.com (Jerry Schwarz (Compiler)) Distribution: comp Organization: Ardent Computer Corp., Sunnyvale, CA Lines: 69 In article thoth@springs.cis.ufl.edu (Robert Forsman) writes: > > I assume you guys have already discussed the idea of an explicit >conversion and trashed it. > > String decimalString(int value,int width); > String hexString(int value,int width); > String decimalString(float value,int width,int decimals=-1); >(and for those manic math lovers like me :^) > String anybaseString(float value,unsigned int base, > int width,int decimals=-1); > > cout << decimalString(4,0); > cout << "Time to impact :" << decimalString(boom,1,2) << '\n'; > Indeed, more than discussed. This is essentially the method used by the AT&T 1.2 stream package. There are several problems with it. Where does the space come from for the string? How about all the twiddles on formatting available in stdio? (e.g. the case of the alphabetic "digits" in a hex number) But you don't have to choose. Its fairly easy to implement the functionality of the above without intermediate strings. One (among several choices) is class decimalString() { public: decimalString(int v, int w) : value(v), width(w) { } int value ; int width ; } ; ostream& operator<< (ostream& o,decimalString& s) { int f = o.flags(); o << dec << setw(s.w) << s.value ; o.setf(p,ios::basefield); return o ; } There is a philosopical point here. In C the builtin types are special. Its perfectly reasonable to have a C I/O library that has a lot of formatting stuff for them. In C++ user defined classes are just as important as the builtin types. What is important is not that there be a lot of formatting stuff for the builtin types, but that there be a mechanism for extending the I/O. In C++ it is usually much better to determine styles of printing, widths and the like based on the role (type) type of the data rather than specifying it at each individual I/O statement. In hindsight I think I put too much special stuff in the iostream library for the builtin types. Historically, what happened was that the builtin type stuff was done first, and only much later did I develop the extensibility features (such as xalloc). > ( side note. I had trouble with that '\n' being converted to an int >before reaching the ostream. I decided to typecast it and that solved >the problem. It was probably just a compiler "bug") This is a well known "feature:-)" in AT&T 1.2. Its been fixed in AT&T 2.0. Jerry Schwarz Disclaimer: I'd usually run code like the above before putting it in a netnews item. In this case I didn't.