home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!rational.com!thor!rmartin
- From: rmartin@thor.Rational.COM (Bob Martin)
- Subject: Re: Questions about iostream. Please help!
- Message-ID: <rmartin.725042821@thor>
- Sender: news@rational.com
- Organization: Rational
- References: <1gt91eINNfrf@miles.mps.ohio-state.edu>
- Date: Tue, 22 Dec 1992 16:47:01 GMT
- Lines: 74
-
- ren@miles.mps.ohio-state.edu (Liming Ren) writes:
-
- |The following program was posted in this group (not by me) a while ago.
-
- |#include <iostream.h>
- |#include <strstream.h>
- |#include <fstream.h>
- |int main( int argc, char ** argv )
- |{
- | istream * is;
- | if( argc == 2 ){
- | is = new ifstream( argv[ 1 ] );
- | }else{
- | is = &cin;
- | }
- | while( *is ){
- | ostrstream out_str;
- | is->get( *out_str.rdbuf( ));
- | is->ignore( 1, '\n' );
- | cout <<out_str.rdbuf( )<< endl;
- | }
-
- | if( argc == 2 ){ // Delete the object created.
- | delete is;
- | }
- | return 0;
- |}
-
-
- |After I study it, I have two questions:
-
- |(1) If I use it as : a.out file1>file2, diff tells me there is an
- |extra newline added to file2 at the end of file. I don't see how this
- |can happen. How to correct it?
-
- I think that there is one extra loop happening at the end. The 'get'
- on the last line terminates before the line-end. The ignore gobbles
- the line end, but the EOF has not been reached. The loop continues
- because EOF has not been reached. The next get extracts nothing
- because it hits the EOF. The ignore finds no line-end. But the cout
- puts one out anyway.
-
- |(1) About the main while loop. It is my understanding that *is is a
- |class instance of istream with the following picyure:
-
- | ______ _____________________
- | | is |---------->| |
- | ------ | |
- | | istream |
- | |___________________|
-
- |How (*is) can be zero and how it is set to zero? Does this mean that
- |the class instance is zero? I am comfused here.
-
- *is points to an istream. An istream is a derivative of class ios.
- ios declares operator void*(). Thus a "user-defined" conversion takes
- place whenever an ios object appears in a conditional syntax. The ios
- is converted to a void*. The void* will be zero if the failbit or
- badbit of the ios is set. Otherwise the void* will be non-zero.
-
- Thus you can do cute things like:
-
- while (cin) {...}
-
- which will loop until cin complains about something, typically EOF.
-
-
-
-
- --
- Robert Martin Training courses offered in:
- R. C. M. Consulting Object Oriented Analysis
- 2080 Cranbrook Rd. Object Oriented Design
- Green Oaks, Il 60048 (708) 918-1004 C++
-