home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!charon.amdahl.com!amdahl!rtech!pacbell.com!ames!agate!stanford.edu!lucid.com!lucid.com!jss
- From: jss@lucid.com (Jerry Schwarz)
- Subject: Re: buffering iostreams
- Message-ID: <1993Jan28.034002.5892@lucid.com>
- Sender: usenet@lucid.com
- Reply-To: jss@lucid.com (Jerry Schwarz)
- Organization: Lucid, Inc.
- References: <1k2co6INN7mm@wilma.cs.widener.edu>
- Date: Thu, 28 Jan 93 03:40:02 GMT
- Lines: 84
-
- In article <1k2co6INN7mm@wilma.cs.widener.edu>, quairoli@cs.widener.edu (Patrick J. Quairoli) writes:
- |> i'm trying to take a long (i.e. 72) and cast it as a char so
- |> that i get a value of 'H'. this can be easily done by:
- |>
- |> long foo = 72;
- |>
- |> cout << (char)foo;
- |>
- |> BUT! i also want the output to be buffered as an long (4 bytes).
- |>
-
- First, what you're talking about is generally called "padding"
- not "buffering", and long's aren't normally padded to 4 characters
- either.
-
- |>
- |> cout << setw(sizeof(long)) << (char)foo;
- |>
- |> which gives me 'H' but it is not buffered (i.e. its' flush with the
- |> left of the screen and there are no trialing spaces). if it were
- |> buffered as a long it would be 'H '.
- |>
-
- Much of the documentation of iostreams says that the char inserter
- pads. But the original AT&T library didn't and most (maybe all)
- of the other implementations have followed the original implementation
- (rather than the original documentation).
-
- The standards committee will probably go along with the existing
- implementations rather than the original documentation and say
- that the char inserter doesn't pad either.
-
- |> if i use:
- |>
- |> cout << setw(sizeof(long)) << foo;
- |>
- |> i get 72 and it is buffered with 2 leading spaces (i.e. two bytes)....
- |>
- |> ? how do i get a long to be cast as a char and still buffer it?
- |>
-
- One way is to use a string rather than a char.
-
- char a[2] ;
- a[0] = foo ;
- a[1] = 0 ;
- cout << setw(sizeof(long)) << a
-
- If you you're going to be doing this much, you might find it convenient
- to wrap it up in a manipulator.
-
- #include <iostream.h>
- #include <iomanip.h>
-
- ostream& paddedcharf(ostream& o, int c) {
- char a[2] ;
- a[0] = c ;
- a[1] = 0 ;
- return o << setw(sizeof(long)) << a ;
- }
-
- OAPP(int) paddedchar(paddedcharf) ;
-
- ...
- cout << paddedchar(foo) ;
-
- I used an "int" manipulator rather than a "long" (as might
- be suggested by the original problem) because iomanip.h declares
- it.
-
- And finally with regard to whether padding comes before
- or after the value. This can be controlled by flags. To get
- the padding after the data instead of before (the default is
- before) you do
-
- cout.setf(ios::left,ios::adjustfield) ;
-
- The flag specifies where the data goes.
-
- -- Jerry Schwarz
-
-
-
-
-