                        20.  iostream

      C++   iostream  -
  ,    , 
 .      
/   .  ,   
         .
   iostream    
 

   #include <iostream>

    /     istream ( ) 
ostream ( ).  , iostream,     
  /.      
 -:

    cin    istream,   .  
            ;
    cout    ostream,   .  
            ;
    cerr    ostream,     .
             .

    ,  ,      
(<<),         (>>):

1029

   #include <iostream>
   #include <string>

   int main()
   {
      string in_string;

    //     
   cout << "  , : ";

   //     in_string
   cin >> in_string;

   if ( in_string.empty() )
      //       
      cerr << ":   !\n";
   else cout << ", " << in_string << "!\n";
}

      ,  ,     
 . ,

   >> x

   x, 

   << x

   x. (  20.1  ,   iostream
  ,    20.5        
.   20.2   ,   20.4  
     .)
          ,  iostream 
    .     :

    ifstream,   istream,     ;
    ofstream,   ostream,     ;
    fstream,   iostream,   ,     
     .

       iostream,   
/,      

   #include <fstream>
   ( fstream   iostream,      .)

    /    :

1030

   #include <fstream>
   #include <string>
   #include <vector>
   #include <algorithm>

   int main()
   {
      string ifile;

      cout << "    : ";
      cin >> ifile;

      //    ifstream    
      ifstream infile( ifile.c_str() );

      if ( ! infile ) {
        cerr << ":     : "
        << ifile << endl;
        return -1;
       }

       string ofile = ifile + ".sort";

   //    ofstream    
   ofstream outfile( ofile.c_str() );
   if ( ! outfile) {
         cerr << ":     : "
         << ofile << endl;
         return -2;
   }

   string buffer;
   vector< string, allocator > text;

   int cnt = 1;
   while ( infile >> buffer ) {
      text.push_back( buffer );
      cout << buffer << (cnt++ % 8 ? " " : "\n" );
   }

   sort( text.begin(), text.end() );

   //      
   vector< string >::iterator iter = text.begin();
   for ( cnt = 1; iter != text.end(); ++iter, ++cnt )
        outfile << *iter
        << (cnt % 8 ? " " : "\n" );

   return 0;
}

         .      .
  alice_emma (     
).       ,   
:

       : alice_emma
   Alice Emma has long flowing red hair. Her
   Daddy says when the wind blows through her
   hair, it looks almost alive, like a fiery
   bird in flight. A beautiful fiery bird, he
   tells her, magical but untamed. "Daddy, shush, there

1031

   is no such creature," she tells him, at
   the same time wanting him to tell her
   more. Shyly, she asks, "I mean, Daddy, is
   there?"

        outfile   .
,      ;     
:

   "Daddy, "I A Alice Daddy Daddy, Emma Her
   Shyly, a alive, almost asks, at beautiful bird
   bird, blows but creature," fiery fiery flight. flowing
   hair, hair. has he her her her, him
   him, in is is it like long looks
   magical mean, more. no red same says she
   she shush, such tell tells tells the the
   there there?" through time to untamed. wanting when
   wind

   (  20.6     /  .)

    iostream   /   ,   
     .    
/           .  
 /       :

    istringstream,   istream,   ;
    ostringstream,   ostream,   ;
    stringstream,   iostream,   ,   .

             


   #include <sstream>

( sstream   iostream,      .) 
    ostringstream   
  ,    .

1032

   #include <sstream>

   string program_name( "our_program" );
   string version( 0.01 );

   // ...

   string mumble( int *array, int size )
   {
      if ( ! array ) {
          ostringstream out_message;

          out_message << ": "
                      << program_name << "--" << version
                      << ": " << __FILE__ << ": " << __LINE__
                      << " --   0; "
                      << "    .\n";

          //  ,    
         return out_message.str();
      }
      // ...
   } 

   (  20.8     /  .)
    /    : char  wchar_t.  
            char.  , 
 iostream          wchar_t.
    ,   char, 
 w. ,     wcin,   
wcout,      wcerr.     
char  wchar_t    .
     /   wchar_t  wostream, wistream,
wiostream,   /  wofstream, wifstream, wfstream,  
  wostringstream, wistringstream, wstringstream.

                               20.1.   <<

            cout.
, 

   #include <iostream>

   int main()
   {
      cout << "  \n";
   }

   :

     


1033

    ,      ,
 const char*,    string  complex   .
 ,   ,     
 ,      ,  -
  . , 

   #include <iostream>
   #include <string.h>

   int main()
   {
      cout << " '' :\t";
      cout << strlen( "" );
      cout << '\n';
      cout << " '' :\t";
      cout << sizeof( "" );
      cout << endl;

}

   :

    '' :7
    '' :8

endl    ,       
  ,      ostream. (  
   20.9.)
    ,  ,     . ,
     :

   #include <iostream>
   #include <string.h>

   int main()
   {
      //    

      cout << " '' :\t";
             << strlen( "" ) << '\n';

      cout << " '' :\t"
             << sizeof( "" ) << endl;
   }

      (  )  ,  


cout << " ";

1034

    , ..   cout.    
       ( ,   <<
).
          , 
  .       .
, 

   #include <iostream>

   int main()
   {
      int i = 1024;
      int *pi = &i;

      cout << "i: " << i
             << "\t&i:\t" << &i << '\n';

      cout << "*pi: " << *pi
             << "\tpi:\t" << pi << endl
             << "\t\t&pi:\t" << &pi << endl;
  }

      :

     i: 1024 &i: 0x7fff0b4
   *pi: 1024 pi: 0x7fff0b4
   &pi: 0x7fff0b0

     ,      .
       .    ,  
 pstr:

   #include <iostream>

   const char *str = "vermeer";
   int main()
   {
      const char *pstr = str;
      cout << " pstr : "
             << pstr << endl;
   }

            :

    pstr : vermeer

     ,   const char*   C-.   
 ,   pstr,     const

1035

char*  .       const,  
 pstr   void*:

   << static_cast<void*>(const_cast<char*>(pstr))

       :

    pstr : 0x116e8

       .      :

   #include <iostream>

   inline void
   max_out( int val1, int val2 )
   {
      cout << ( val1 > val2 ) ? val1 : val2;
   }

   int main()
   {
      int ix = 10, jx = 20;

      cout << "  " << ix
             << ", " << jx << "  ";

      max_out( ix, jx );

      cout << endl;
   }

       :

     10, 20  0

     ,       ,  
 ,     val1  val2. 
, 

   cout << ( val1 > val2 ) ? val1 : val2;

 

   (cout << ( val1 > val2 )) ? val1 : val2;

    val1   val2,     false, 
.    ,     
  :

   cout << ( val1 > val2 ? val1 : val2 );

      : 

1036

     10, 20  20

         ,     true  false
 bool   ,    1  0.     :

     10, 20  false

    .    false   0,  true   1. 
 ,   boolalpha(),    
 :

   int main()
   {
      cout << "   bool  : "
             << true << " " << false
             << "\n   : "
             << boolalpha()
             << true << " " << false
            << endl;
   }

    :

      bool  : 1 0
      : true false

     ,     ,    
    :

   #include <iostream>
   #include <vector>
   #include <string>

   string pooh_pals[] = {
              "", "", "-", ""
   };

   int main()
   {
      vector<string> ppals( pooh_pals, pooh_pals+4 );

      vector<string>::iterator iter = ppals.begin();
      vector<string>::iterator iter_end = ppals.end();

         cout << "  : ";
         for ( ; iter != iter_end; iter++ )
            cout << *iter << " ";

         cout << endl;
}

1037

          ,    ,
    ostream_iterator.  
 ,     ( 
 ostream_iterator .   12.4):

   #include <iostream>
   #include <algorithm>
   #include <vector>
   #include <string>

   string pooh_pals[] = {
             "", "", "-", ""
    };

   int main()
   {
         vector<string> ppals( pooh_pals, pooh_pals+4 );

         vector<string>::iterator iter = ppals.begin();
         vector<string>::iterator iter_end = ppals.end();

                 cout << "  : ";

         //     cout ...
           ostream_iterator< string > output( cout, " " );
           copy( iter, iter_end, output );

           cout << endl;
}

      :

     :   - 

                          20.1

         :

   string sa[4] = { "", "", "", "-" };
   vector< string > svec( sa, sa+4 );
   string robin( " " );
   const char *pc = robin.c_str();
   int ival = 1024;
   char blank = ' ';
   double dval = 3.14159;
   complex purei( 0, 7 );

   (a)       .
   (b)    pc.

1038

   (c)      ival  dval,  
        :

   ival < dval ? ival : dval


                                 20.2. 

            (>>). , 
        
int    :

   #include <iostream>
   #include <vector>

   int main()
   {
      vector<int> ivec;
      int ival;

      while ( cin >> ival )
            ivec.push_back( ival );
      // ...
   }

   

    cin >> ival;

           ival.
       istream,    cin. (
 ,     .)
   

   while ( cin >> ival )

  ,  cin    false.  istream
   false   :    (..   
  )    ,  3.14159
(     ), 1e-1 ( e )  
 .    ,  istream  
    . (  20.7    
 .)
       ,   
 ,  C-,      string 
complex:

1039

   #include <iostream>
   #include <string>

   int main()
   {
      int item_number;
      string item_name;
      double item_price;

      cout << ",  item_number, item_name  price: "
             << endl;

      cin >> item_number;
      cin >> item_name;
      cin >> item_price;

      cout << " : item# "
             << item_number << " "
             << item_name << " @$"
             << item_price << endl;
   }

       :

   ,  item_number, item_name  price:
      10247 widget 19.99
    : item# 10247 widget @$19.99

         .    
    : ,  , 
   ,       . ( ,
   , .   20.9.)

   ,  item_number, item_name  price:
   10247
   widget
    19.99
    : item# 10247 widget @$19.99

      iostream  ,   .    
:

   // : item_name   
   BuzzLightyear 10009 8.99

    

   cin >> item_number;

  ,  BuzzLightyear    int. 
  istream   false,   
.       :

1040

   cin >> item_number;
   if ( ! cin )
   cerr << ":    item_number!\n";

       ,   
  ,       ,
  .     :

   #include <iostream>
   #include <string>

   int main()
   {
      int item_number;
      string item_name;
      double item_price;

      cout << ",  item_number, item_name  price: "
             << endl;

      // ,    
      cin >> item_number >> item_name >> item_price;

      cout << " : item# "
             << item_number << " "
             << item_name << " @$"
             << item_price << endl;
   }

   

   ab c
   d e

   : 'a', 'b', ' ' (), 'c', '\n' (  
), 'd', '\t' (), 'e'  '\n'.     
 :

   #include <iostream>

   int main()
   {
      char ch;

      //     
     while ( cin >> ch )
         cout << ch;
      cout << endl;

      // ...
   }

1041

  :

   abcde

        .     , 
         (, 
      ),   
- get()  istream (      -
 put()  ostream;    ). :

   #include <iostream>

   int main()
   {
      char ch;

      //   ,    
      while ( cin.get( ch ))
            cout.put( ch );
  
        // ...
   }

          noskipws.
            ,
 ,         const
char*  string:

   A fine and private place
   "A fine and private place"

            . 
      ,   
  .
            , 
   istream_iterator:

1042

   #include <algorithm>
   #include <string>
   #include <vector>
   #include <iostream>

   int main()
   {
      istream_iterator< string > in( cin ), eos ;
      vector< string > text ;

      //      
      //   text
      copy( in , eos , back_inserter( text ) ) ;

      sort( text.begin() , text.end() ) ;

      //  
      vector< string >::iterator it;
      it = unique( text.begin() , text.end() ) ;
      text.erase( it , text.end() ) ;

      //   
      int line_cnt = 1 ;
      for ( vector< string >::iterator iter = text.begin() ;
      iter != text.end() ; ++iter , ++line_cnt )
          cout << *iter
                 << ( line_cnt % 9 ? " " : "\n" ) ;

           cout << endl;
   }

          istream_iter.C   . 
 UNIX         
(istream_iter     ):

   istream_iter < istream_iter.C

   (     .)   
:

   != " " "\n" #include % ( ) *iter ++iter
   ++line_cnt , 1 9 : ; << <algorithm> <iostream.h>
   <string> <vector> = > >::difference_type >::iterator ? allocator
   back_inserter(
   cin copy( cout diff_type eos for in in( int
   istream_iterator< it iter line_cnt main() sort( string test test.begin()
   test.end() test.erase( typedef unique( vector< { }

(  / iostream    12.4.)
   ,    
       .
(       20.5.)

1043

                             20.2.1.  

        C-,      string. 
  .     
    .     C-, ..
 ,     ,   
.      ,      
,      ,     
  :

   #include <iostream>
   #include <string.h>

   char inBuf[ 1024 ];
   try
   {
      while ( cin >> inBuf ) {
         char *str = new char[ strlen( inBuf ) + 1 ];
         strcpy( str, inBuf );
         // ...  -    str
         delete [] str;
      }
   }
  catch( ... ) { delete [] str; throw; }

      string  :

   #include <iostream>
   #include <string.h>

   string str;
   while ( cin >> str )
      // ...  -  

    C-     string.   
 -      :

   Alice Emma has long flowing red hair. Her Daddy says
   when the wind blows through her hair, it looks almost
   alive, like a fiery bird in flight. A beautiful fiery
   bird, he tells her, magical but untamed. "Daddy, shush,
   there is no such creature," she tells him, at the same time
   wanting him to tell her more. Shyly, she asks, "I mean,
   Daddy, is there?"

        alice_emma,      
 . ,      ,   
   .     
    C-     :

1044

   #include <iostream.h>
   #include <string.h>

   int main()
   {
      const int bufSize = 24;
      char buf[ bufSize ], largest[ bufSize ];

      //   
      int curLen, max = -1, cnt = 0;
      while ( cin >> buf )
      {
         curLen = strlen( buf );
         ++cnt;

          //    ?  
         if ( curLen > max ) {
             max = curLen;
             strcpy( largest, buf );
         }
      }
      cout << "   "
             << cnt << endl;

       cout << "    "
              << max << endl;

      cout << "   "
             << largest << endl;
   }


          :

      65
       10
      creature,"

        :    beautiful,   
.   creature,        
. ,    .
    ,   .    
   buf,    24.      
 24  ( ),      , ,
  .     , 
  setw().   :

   while ( cin >> setw( bufSize ) >> buf )

    bufSize     buf. setw()    bufSize
    ,     ,  bufSize - 1.
     .   setw() 
     iomanip:

   #include <iomanip>

1045

       buf    :

    char buf[] = " ";

     sizeof,   ,  
        :

   while ( cin >> setw(sizeof( buf )) >> buf )

     sizeof      :

   #include <iostream>
   #include <iomanip>

   int main()
   {
      const int bufSize = 24;
      char buf[ bufSize ];
      char *pbuf = buf;

      //   ,  sizeof(char*),
      //     

      while ( cin >> setw( sizeof( pbuf )) >> pbuf )
         cout << pbuf << endl;
   }

    :

   $ a.out
   The winter of our discontent

   The
   win
   ter
   of
   our
   dis
   con
   ten
   t

    setw()      ,   
    ,        .
        :

   while ( cin >> setw(sizeof( *pbuf )) >> pbuf )

      setw()  ,  pbuf.  

   *pbuf

   , ..   char.  setw()   1.
    while  ,    pbuf, 

1046

  .          ,
 .
      string     ,  
  string.        :

  #include <iostream.h>
   #include <string>

   int main()
   {
       string buf, largest;

      //   
      int curLen, //   
           max = -1, //   
           cnt = 0; //   

      while ( cin >> buf )
      {
         curLen = buf.size();
         ++cnt;
          
        //    ?  
        if ( curLen > max )
        {
           max = curLen;
           largest = buf;
        }
      }

      cout << "   " << cnt << endl;
      cout << "    " << max << endl;
      cout << "   " << largest << endl;

   }

       -   .   
    :

   #include <string>
   void filter_string( string &str )
   {
       // ,  
       string filt_elems( "\",?." );
       string::size_type pos = 0;
       while (( pos = str.find_first_of( filt_elems, pos ))
                != string::npos )
            str.erase( pos, 1 );
  }

      ,   ,   
,   .      
,   .       , 
   .

1047


   #include <string>
   void filter_string( string &str,
                            string filt_elems = string("\",."))
   {
      string::size_type pos = 0;
      while (( pos = str.find_first_of( filt_elems, pos ))
                 != string::npos )
         str.erase( pos, 1 );
   }

      filter_string()   , 
,   :

   template <class InputIterator>
   void filter_string( InputIterator first, InputIterator last,
  	               string filt_elems = string("\",."))
   {
      for ( ; first != last; first++ )
      {
         string::size_type pos = 0;
         while (( pos = (*first).find_first_of( filt_elems, pos ))
                     != string::npos )
            (*first).erase( pos, 1 );
      }
   }

       :

1048

   #include <string>
   #include <algorithm>
   #include <iterator>
   #include <vector>
   #include <iostream>

   bool length_less( string s1, string s2 )
   { return s1.size() < s2.size(); }

   int main()
   {
        istream_iterator< string > input( cin ), eos;

           vector< string > text;
      // copy -   
          copy( input, eos, back_inserter( text ));

          string filt_elems( "\",.;:");
          filter_string( text.begin(), text.end(), filt_elems );

          int cnt = text.size();
       // max_element -   
          string *max = max_element( text.begin(), text.end(),
                                                    length_less );
           int len = max->size();

        cout << "   "
               << cnt << endl;

         cout << "    "
               << len << endl;
              
         cout << "   "
                << *max << endl;
   }

        max_element()   ,
   string,     :

      65
       4
      wind

   ,  wind      . ,   
 string     ,    .   
 wind    .     
 ,      
length_less().    :

      65
       9
      beautiful


                               20.2

1049

          : string,
double, string, int, string.   ,     .

                               20.3

          .   
.       .

                   20.3.   /

          
 ,   , ,  char, int, string  .. -
 get()  istream    ,   getline()  ,
      ,  - 
,  .  - get()   :

    get(char& ch)       (    ) 
        ch.    iostream,    .

  ,       ,  
    :

   #include <iostream>

   int main()
   {
      char ch;
      int tab_cnt = 0, nl_cnt = 0, space_cnt = 0,
           period_cnt = 0, comma_cnt = 0;
      while ( cin.get(ch)) {
          switch( ch ) {
             case ' ': space_cnt++; break;
             case '\t': tab_cnt++; break;
             case '\n': nl_cnt++; break;
             case '.': period_cnt++; break;
             case ',': comma_cnt++; break;
        }
        cout.put(ch);
    }

     cout << "\n :\n\t"
            << ": " << space_cnt << '\t'
            << "  : " << nl_cnt << '\t'
             << ": " << tab_cnt << "\n\t"
             << ": " << period_cnt << '\t'
             << ": " << comma_cnt << endl;
   }

   - put()  ostream     
     : put()    char   
    ostream,    .

          :

   Alice Emma has long flowing red hair. Her Daddy says
   when the wind blows through her hair, it looks almost alive,
   like a fiery bird in flight. A beautiful fiery bird, he tells her,

1050

   magical but untamed. "Daddy, shush, there is no such creature,"
   she tells him, at the same time wanting him to tell her more.
   Shyly, she asks, "I mean, Daddy, is there?"

    :
        : 59   : 6 : 0
        : 4 : 12

      get()        , 
        istream,    .  
       int,   char,      
      ,    -1,     
     .          
      EOF,     iostream. , 
       ,  get(),     int,
               ,   EOF:

   #include <iostream>

   int main()
   {
       int ch;

      // :
     // while ( ch = cin.get() && ch != EOF )
     while (( ch = cin.get()) != EOF )
        cout.put( ch );
     return 0;
   }

         get()    
     :

   a b c
   d

     : ('a', , 'b', , 'c',   ,
   'd').     EOF.   (>>)  
     ,      
    ,    : 'a', 'b', 'c', 'd'.  
     get()       
   ;

       get() :

   get(char *sink, streamsize size, char delimiter='\n')

   sink   ,    . size    
   ,    istream. delimiter   -, 
      .    , 
         .   
           get().   

1051

   ,       -
   ignore()  istream.      
   .
      ,       
   .    ,     
    .

     size-1 ;
      ;
     - (  ,     
        ).

     get()   istream,     (-
    gcount()     ).  
     :

   #include <iostream>

   int main()
   {
      const int max_line = 1024;
      char line[ max_line ];

      while ( cin.get( line, max_line ))
      {
         //    max_line - 1 ,
         //     
        int get_count = cin.gcount();
       cout << "  : "
              << get_count << endl;
       // -   
       //     ,
       //  ,      
      if ( get_count < max_line-1 )
         cin.ignore();
     }
  }

             ,   
 :

     : 52
     : 60
     : 66
     : 63
     : 61
     : 43

        ,   , 
 max_line ,      . :

     : 1023

1024;

1052

     : 528
     : 52
     : 60
     : 66
     : 63
     : 61
     : 43

     ignore()       ,   ,
         .  
   :

   ignore( streamsize length = 1, int delim = traits::eof )

ignore()    length       
         istream, 
 .
       getline(),   get(),  
    .  getline()  ,  
get()    (     istream,  
):

   getline(char *sink, streamsize size, char delimiter='\n')

     getline(),  get()      size  
,       istream,   
 .    - gcount():  
 ,      get()  getline().
   - write()  ostream     
.        ,  
  ,    ,   .  
:

   write( const char *sink, streamsize length )

    length ,   . write()  
 ostream,    .
      write()   ostream   read()  
istream   :

   read( char* addr, streamsize size )

read()  size        ,   
addr.  gcount()   ,   
  read().    read()    istream, 
  .    getline(), gcount()  write():

1053


   #include <iostream>

   int main()
   {
      const int lineSize = 1024;
      int lcnt = 0; //   
      int max = -1; //    

     char inBuf[ lineSize ];

     //    ,    1024 
     while (cin.getline( inBuf, lineSize ))
     {
         //    
         int readin = cin.gcount();

         // :  ,   
        ++lcnt;
        if ( readin > max )
           max = readin;

        cout << " #" << lcnt
               << "\t : " << readin << endl;

        cout.write( inBuf, readin).put('\n').put('\n');
      }
      cout << "  : " << lcnt << endl;
      cout << "  : " << max << endl;
   }

               ,
  :

    #1  : 45
   Call me Ishmael. Some years ago, never mind

    #2  : 46
   how long precisely, having little or no money

    #3  : 48
   in my purse, and nothing particular to interest

    #4  : 51
   me on shore, I thought I would sail about a little

    #5  : 47
   and see the watery part of the world. It is a

    #6  : 43
   way I have of driving off the spleen, and

    #7  : 28
   regulating the circulation.

     : 7
     : 51

   - getline()  istream      .
       getline(),  
    string:

1054

   getline( istream &is, string str, char delimiter );

        str::max_size()-1 .  
 ,        
 .     ,  
 (   ,     )   
.
        -  istream:

   //    
   putback( char class );

   //  "     istream  
       
   unget();

   //    ( EOF),
   //      
   peek();

         :

   char ch, next, lookahead;

   while ( cin.get( ch ))
   {
       switch (ch) {
       case '/':
          //  ?    peek()
          //  ,   
          next = cin.peek();
          if ( next == '/' )
             cin.ignore( lineSize, '\n' );
          break;
       case '>':
          //    >>=
         next = cin.peek();
         if ( next == '>' ) {
            lookahead = cin.get();
            next = cin.peek();
            if ( next != '=' )
               cin.putback( lookahead );
       }
          // ...
   }

                                   20.4

         , 
 ,        (-):

   a b c
   d e
   f

1055

                                    20.5

     riverrun, from bend of bay to swerve of shore  
   ,     .

                                    20.6

      getline()  gcount()    
      ( ,  ,  
   getline(),   ).


                          20.4.   

     ,       /, 
    .     ,
   . (     
.) ,   WordCount   :

   class WordCount {
   friend ostream&
       operator<<( ostream&, const WordCount& );
   public:
      WordCount( string word, int cnt=1 );
      // ...
   private:
      string word;
      int occurs;
   };

   ostream&
   operator <<( ostream& os, const WordCount& wd )
   { //: <> 
      os << "< " << " > " > "
          << wd.word;
     return os;
  }

     ,      
.    :       
  ,        
 .     WordCount   
     :

   #include <iostream>
   #include "WordCount.h"

   int main()
   {
      WordCount wd( "sadness", 12 );
      cout << "wd:\n" << wd << endl;
     return 0;
   }


1056

       :

   wd:
   <12> sadness

        ,      
ostream.        
 :

   //    
   ostream&
   operator <<( ostream& os, const ClassType &object )
   {
      //     
      //   
      os << // ...
      //   ostream
      return os;
   }

           ostream,     (
)    .    ostream. 
   ostream,    .
       ,     
  ,    . ( .   15.1.)  
    ,      . (
    15.2.)
    Location   ,        
.   :

   #include <iostream>

   class Location {
   friend ostream& operator<<( ostream&, const Location& );
   private:
      short _line;
      short _col;
   };

   ostream& operator <<( ostream& os, const Location& lc )
   {
      //  Loc   : < 10,37 >
      os << "<" << lc._line
          << "," << lc._col << "> ";
      return os;
   }

      WordCount,     occurList 
Location   word  string:



1057

   #include <vector>
   #include <string>
   #include <iostream>
   #include "Location.h"

   class WordCount {
   friend ostream& operator<<( ostream&, const WordCount& );
   public:
      WordCount() {}
      WordCount( const string &word ) : _word( word ) {}
      WordCount( const string &word, int ln, int col )
         : _word( word ) { insert_location( ln, col ); }
              
      string word() const { return _word; }
      int occurs() const { return _occurList.size(); }
      void found( int ln, int col )
         { insert_location( ln, col ); }
  private:
     void insert_location( int ln, int col )
     { _occurList.push_back( Location( ln, col )); }
     string _word;
     vector< Location > _occurList;
   };

     string  Location    operator<<().  
     WordCount:

   ostream&
   operator <<( ostream& os, const WordCount& wd )
   {
      os << "<" << wd._occurList.size() << "> "
           << wd._word << endl;

      int cnt = 0, onLine = 6;
      vector< Location >::const_iterator first =
            wd._occurList.begin();
      vector< Location >::const_iterator last =
         wd._occurList.end();

     for ( ; first != last; ++first )
     {
          // os << Location
         os << *first << " ";

        // :  6  
        if ( ++cnt >= onLine )
        { os << "\n"; cnt = 0; }
   }
   return os;
   }

            WordCount;
      :

1058

   int main()
   {
 
      WordCount search( "rosebud" );

     //     8 
      search.found(11,3); search.found(11,8);
      search.found(14,2); search.found(34,6);
      search.found(49,7); search.found(67,5);
      search.found(81,2); search.found(82,3);
      search.found(91,4); search.found(97,8);

      cout << ": " << "\n"
             << search << endl;

      return 0;
   }

         :

   :
   <10> rosebud
   <11,3> <11,8> <14,2> <34,6> <49,7> <67,5>
   <81,2> <82,3> <91,4> <97,8>

        output.     , 
      .

                                  20.7

      Date:

   class Date {
   public:
      // ...
   private:
      int month, day, year;
  };

      :

(a)
   //   
   September 8th, 1997

(b)
      9 / 8 / 97

(c)   ? .

(d)     Date  -? ?

                             20.8

         CheckoutRecord:

1059

   class CheckoutRecord { //   
   public:
      // ...
   private:
      double book_id; //  
      string title; // 
      Date date_borrowed; //  
      Date date_due; //  
      pair<string,string> borrower; //  
      vector pair<string,string> wait_list; //   
   };


                           20.5.   

      (>>)     , , 
,     . , ,  
  WordCount:

1060

   #include <iostream>
   #include "WordCount.h"

   /*     WordCount, 
         
      class WordCount {
      friend ostream& operator<<( ostream&, const WordCount& );
      friend istream& operator>>( istream&, const WordCount& );
   */

   istream&
   operator >>( istream &is, WordCount &wd )
   {
      /*    WordCount:
      * <2> 
      * <7,3> <12,36>
   */

   int ch;

   /*   '<'.   ,
   *       
   */
   if ((ch = is.get()) != '<' )
   {
      // is.setstate( ios_base::badbit );
      return is;
   }

   //  
   int occurs;
   is >> occurs;

   //    >;   
   while ( is && (ch = is.get()) != '>' ) ;

   is >> wd._word;

   //   ;
   //    : < ,  >
   for ( int ix = 0; ix < occurs; ++ix )
   {
      int line, col;
      //  
      while (is && (ch = is.get())!= '<' ) ;
      is >> line;

      while (is && (ch = is.get())!= ',' ) ;
      is >> col;

      while (is && (ch = is.get())!= '>' ) ;

      wd._occurList.push_back( Location( line, col ));
   }
   return is;

}

         ,    
   :

1061

     ,     -  ,
         fail:

      is.setstate( ios_base::failbit );

         ,   
     ,  :

     while (( ch = is.get() ) != lbrace)

      ,   istream    
     .      get()  
     :

          // ,    "is"  "" 
     while ( is && ( ch = is.get() ) != lbrace)

       istream    ,     
     false. (       20.7.)

        WordCount,   
  :

   #include <iostream>
   #include "WordCount.h"

   int main()
   {
      WordCount readIn;

      // operator>>( cin, readIn )
      cin >> readIn;

      if ( !cin ) {
         cerr << "  WordCount" << endl;
         return -1;
      }

      // operator<<( cout, readIn )
     cout << readIn << endl;
   }

 :

   <10> rosebud
   <11,3> <11,8> <14,2> <34,6> <49,7> <67,5>
   <81,2> <82,3> <91,4> <97,8>


                                  20.9

      WordCount     Location.  
      Location.

1062

                                   20.10

        Date   20.7   20.4.

                                   20.11

        CheckoutRecord   20.8  
20.4.

                                20.6.  /

        ,      
 fstream (     iostream):

   #include <fstream>

         ,    
ofstream. :

   ofstream outfile( "copy.out", ios::base::out );

           
.   ofstream         
 (ios_base::out),     (ios_base::app).  
 outfile2   :

   ofstream outfile2( "copy.out" );

         ,     
 .      ,   ,  
    :      . 
   ,      .
             ,  , 
   :

   if ( ! outfile ) { //    
      cerr << "   "copy.out"  \n";
      exit( -1 );
   }

    ofstream    ostream.    ostream
    ofstream. , 

   char ch = ' ';
   outFile.put( '1' ).put( ')' ).put( ch );
   outFile << "1 + 1 = " << (1 + 1) << endl;


1063

   outFile  :

   1) 1 + 1 = 2

              
 :

   #include <fstream>

   int main()
   {
      //   copy.out  
      ofstream outFile( "copy.out" );

      if ( ! outFile ) {
         cerr << "   'copy.out'  \n";
         return -1;
      }

      char ch;
      while ( cin.get( ch ) )
           outFile.put( ch );
  }

      ofstream      
 .       WordCount 
 :

   #include <fstream>
   #include "WordCount.h"

   int main()
   {
      //   word.out  
      ofstream oFile( "word.out" );
     //     ...

     //      WordCount
      WordCount artist( "Renoir" );
      artist.found( 7, 12 ); artist.found( 34, 18 );

      //   <<(ostream&, const WordCount&);
      oFile << artist;
   }

        ,    ifstream,
  istream.      
      :

1064

   #include <fstream>
   #include <string>

   int main()
   {
      cout << "filename: ";
      string file_name;

      cin >> file_name;

      //    
      ifstream inFile( file_name.c_str() );

      if ( !inFile ) {
           cerr << "    : "
                  << file_name << " --  !\n";
           return -1;
      }

      char ch;
      while ( inFile.get( ch ))
         cout.put( ch );
   }

   ,  ,     alice_emma,   
  filter_string() (.  20.2.1,    
   ),  ,    
   :

1065

   #include <fstream>
   #include <iterator>
   #include <vector>
   #include <algorithm>

   template <class InputIterator>
   void filter_string( InputIterator first, InputIterator last,
                           string filt_elems = string("\",?."))
   { 
      for ( ; first != last; first++ )
      {
         string::size_type pos = 0;
         while (( pos = (*first).find_first_of( filt_elems, pos ))
                    != string::npos )
             (*first).erase( pos, 1 );
      }
   }

   int main()
   {
      ifstream infile( "alice_emma" );

      istream_iterator<string> ifile( infile );
      istream_iterator<string> eos;

      vector< string > text;
      copy( ifile, eos, inserter( text, text.begin() ));

      string filt_elems( "\",.?;:" );
      filter_string( text.begin(), text.end(), filt_elems );

      vector<string>::iterator iter;

      sort( text.begin(), text.end() );
      iter = unique( text.begin(), text.end() );
      text.erase( iter, text.end() );

      ofstream outfile( "alice_emma_sort" );

      iter = text.begin();
      for ( int line_cnt = 1; iter != text.end();
         ++iter, ++line_cnt )
      {
          outfile << *iter << " ";
          if ( ! ( line_cnt % 8 ))
             outfile << '\n';
      }
      outfile << endl;
   }

         :

   A Alice Daddy Emma Her I Shyly a
   alive almost asks at beautiful bird blows but
   creature fiery flight flowing hair has he her
   him in is it like long looks magical
   mean more no red same says she shush
   such tell tells the there through time to
   untamed wanting when wind

1066

     ofstream  ifstream      
.          -
open():

   ifstream curFile;
   // ...
   curFile.open( filename.c_str() );
   if ( ! curFile ) //  ?
     // ...

      (  ),  - close():

   #include <fstream>

   const int fileCnt = 5;
   string file_Tabl[ fileCnt ] = {
       "Melville", "Joyce", "Musil", "Proust", "Kafka"
    };

   int main()
   {
      ifstream inFile; //      

      for ( int ix = 0; ix < fileCnt; ++ix )
      {
         inFile.open( file_Tabl[ix].c_str() );
         // ...   
         // ...  
         inFile.close();
     }
    }

     fstream (  iostream)      
.     word.out  ,  
     fstream.      
word.out   WordCount:

1067

   #include <fstream>
   #include "WordCount.h"

   int main()
   {
      WordCount wd;
      fstream file;

      file.open( "word.out", ios::in );
      file >> wd;
      file.close();

      cout << ": " << wd << endl;

      //  ios_base::out    
      file.open( "word.out", ios::app );
      file << endl << wd << endl;
      file.close();
   }

     fstream         .
,     word.out    :

   fstream io( "word.out", ios_base::in|ios_base::app );

          .  
fstream     - seekg()  seekp().
  g     (getting)  (
   ofstream),  p    (putting)  ( 
  ifstream).        , 
     .     :

    seekg( off_type offset_position, ios_base::seekdir dir );

            ,
  current_position,   0  
. ,      :

   abc def ghi jkl

    

   io.seekg( 6 );

 io   , ..  f.    
       ,      
     dir,     :

1068

    ios_base::beg    ;
    ios_base::cur    ;
    ios_base::end    .

        seekg()    i- :

   for ( int i = 0; i < recordCnt; ++i )
     readFile.ssekg( i * sizeof(Record), ios_base::beg );

          .  
10     :

   readFile.seekg( -10, ios_base::cur );

         fstream     -
 tellg()  tellp().  'p'   (putting)   
 ofstream,  'g'    (getting)    ifstream:

   //   
   ios_base::pos_type mark = writeFile.tellp();
   // ...
   if ( cancelEntry )
      //    
      writeFile.seekp( mark );

              Record, 
     :

   //   seekg
   readFile.seekg( readFile.tellg() + sizeof(Record) );

   //     
   readFile.seekg( sizeof(Record), ios_base::cur );

     .   ,       
    .  ,       
      .    :

   abcd
   efg
   hi
   j

      ,   :

1069

   abcd
   efg
   hi
   j
   5 9 12 14 24

       :

   #include <iostream>
   #include <fstream>

   main() {

      //      
      fstream inOut( "copy.out", ios_base::in|ios_base::app );
      int cnt = 0; //  
     char ch;

      while ( inOut.get( ch ))
      {
         cout.put( ch ); //   
         ++cnt;
         if ( ch == '\n' ) {
             inOut << cnt ;
             inOut.put( ' ' ); // 
         }
      }

      //     
      inOut << cnt << endl;
      cout << "[ " << cnt << " ]" << endl;
      return 0;
   }

inOut     fstream,    copy.out,   
 .      ,      
.
      ( ) ,   ,  
 cnt  1      ,  
    .
      ,     cnt  inOut. 
    ,  .   cnt
     .
         .     
       :

   Call me Ishmael. Some years ago, never mind
   how long precisely, having little or no money
   in my purse, and nothing particular to interest
   me on shore, I thought I would sail about a little
   and see the watery part of the world. It is a
   way I have of driving off the spleen, and
   regulating the circulation.

      :

1070

   [ 0 ]

        , , ,   .  
,          .  


   inOut.get( ch );

   ,  while     0.
    ,    , 
 .        . 
   :

   inOut.seekg( 0 );

     .     :

   Call me Ishmael. Some years ago, never mind
   [ 45 ]

    ,         ,   
 .   ,      
.     ,      .  
     cnt,     .  
  get()   ,   while  
.
          ,      cnt. 
    :

   //   
   ios_base::pos_type mark = inOut.tellg();
   inOut << cnt << sp;
   inOut.seekg( mark ); //  

           . 
   ,  ,       :
     ,    .  ,
   while,   .
     ,  inOut     ,     
  .        
 - clear():

   inOut.clear(); //   

       :

1071

   #include <iostream>
   #include <fstream>

   int main()
   {
      fstream inOut( "copy.out", ios_base::in|ios_base::app );
      int cnt=0;
      char ch;

      inOut.seekg(0);

      while ( inOut.get( ch ))
      {
         cout.put( ch );
         cnt++;
         if ( ch == '\n' )
         {
            //   
            ios_base::pos_type mark = inOut.tellg();
            inOut << cnt << ' ';
            inOut.seekg( mark ); //  
        }
   }
   inOut.clear();
   inOut << cnt << endl;
   cout << "[ " << cnt << " ]\n";
   return 0;
   }

      -!   .     
   ,    . 
         
  .

                               20.12

        Date,     
20.7,    CheckoutRecord   20.8 (.  20.4), 
,       .

                                20.13

         ,    20.12.
     .

                                 20.14

       ,    20.12,   
.    Date  CheckoutRecord:

(a)   
(b)     
(c)   

1072


                                  20.7.  

     iostream, , ,    
 . ,   

   int ival;
   cin >> ival;

   "Borges",  cin      
     .      1024, 
          .
    ,     ,    
 :

   if ( !cin )
     //        

             while:

      while ( cin >> word )
      //     ...

      while   false,      
  .       
.        WordCount  
20.5      .
        ,       
.    -:

    eof()  true,    :

      if ( inOut.eof() )
      // :   ...

    bad()  true     , 
          .     , 
         ;
    fail()  true,    ,   
           :

1073

   error_message( ... );
   ifstream iFile( filename, ios_base::in );
   if ( iFile.fail() ) //   
      error_message( ... );

    good()  true,     :

   if ( inOut.good() )

          iostream.  
- clear()     . 
setstate()   ,     ,   
. ,       WordCount  
    setstate()    fail  
 istream:

   if ((ch = is.get()) != '<' )
   {
      is.setstate( ios_base::failbit );
      return is;
   }

       :

   ios_base::badbit
   ios_base::eofbit
   ios_base::failbit
   ios_base::goodbit

           :

   is.setstate( ios_base::badbit | ios_base::failbit );

         WordCount (.  20.5)  :

   if ( !cin ) {
      cerr << "  WordCount" << endl;
      return -1;
   }

   ,        ,
       .   
    cin      . 
    - clear():

   cin.clear(); //  

1074

       clear()       
    . :

   cin.clear( ios_base::goodbit );

   . (  , 
goodbit   clear()   .)
   - rdstate()     :

   ios_base::iostate old_state = cin.rdstate();
   cin.clear();
   process_input();
   //   cin   
   cin.clear( old_state );


                                20.15

     ( )     Date   20.7 /
 CheckoutRecord   20.8 (.  20.4) ,  
   istream.  ,  
    ,    
,        .  , 
     .

                             20.8.  

   iostream       .
 ostringstream    , istringstream   
 ,  stringstream     ,   
.     ,    
 

   #include <sstream>

   ,      alice_emma   buf 
ostringstream.  buf    ,   
:

1075

   #include <string>
   #include <fstream>
   #include <sstream>

   string read_file_into_string()
   {
      ifstream ifile( "alice_emma" );
      ostringstream buf;
      char ch;
      while ( buf && ifile.get( ch ))
         buf.put( ch );
     return buf.str();
   }

   - str()      string,  
  ostringstream.      ,  
   string. ,    text 
 ,   buf:

   int main()
   {
      string text = read_file_into_string();

      //      
      vector< string::size_type > lines_of_text;
      string::size_type pos = 0;

      while ( pos != string::npos )
      {
         pos = text.find( '\n' pos );
         lines_of_text.push_back( pos );
      }
      // ...
   }

     ostringstream    
  , .. ,     .
,        
   ,     
   :

1076

   #include <iostream>
   #include <sstream>

   int main()
   {
      int ival = 1024; int *pival = &ival;
      double dval = 3.14159; double *pdval = &dval;

      ostringstream format_message;

      //     
      format_message << "ival: " << ival
                               << "  ival: " << pival << 'n'
                               << "dval: " << dval
                               << "  dval: " << pdval << endl;

      string msg = format_message.str();
      cout << "   : " << msg.size()
             << " : " << msg << endl;
   }

          ,     
 .        
:

   string
   format( string msg, int expected, int received )
   {
      ostringstream message;
      message << msg << " : " << expected
                    << " : " << received << "\n";
      return message.str();
   }

   string format( string msg, vector<int> *values );
   // ...   

            
   .      Notify
(), Log ()  Error ().
    istringstream     string,    
.  ,     
     :

1077

   #include <iostream>
   #include <sstream>
   #include <string>

   int main()
   {
      int ival = 1024; int *pival = &ival;
      double dval = 3.14159; double *pdval = &dval;

      //  ,     
      ostringstream format_string;

      format_string << ival << " " << pival << " "
                         << dval << " " << pdval << endl;

      //      ASCII
      //       
      istringstream input_istring( format_string.str() );

      input_istring >> ival >> pival
         >> dval >> pdval;
   }


                               20.16

            
 printf(). ,  

   int ival = 1024;
   double dval = 3.14159;
   char cval = 'a';
   char *sval = "the end";
   printf( "ival: %d\tdval% %g\tcval: %c\tsval: %s",
   ival, dval, cval, sval );

   :

   ival: 1024 dval: 3.14159 cval: a sval: the end

     printf()   .   % ,
       ,    
    .     
(  .  [KERNIGHAN88]):

   %d  
   %g    
   %c char
   %s C-


1078

     printf()     
 ,    %.    
       .
    printf() : -, 
      , , -,   
     ,    , 
   .    printf()    
 .

   1.         
      ostringstream.
    2.      .


                         20.9.  

        iostream   ,
    ,  
           .
        
  .1    
  ,   .       
   . ,     bool,
  true (    true),    1:

   #include <iostream.h>

   int main()
   {
       bool illustrate = true;
       cout << " illustrate  bool   true: "
              << illustrate << '\n';
   }

  cout   illustrate    true,  
 boolalpha:


1  ,       
   - setf()  unsetf().   
 ;    ,    , 
  [STROUSTRUP97].

1079

       ,    , 
        .  
       :

   #include <iostream.h>

   int main()
   {
      bool illustrate = true;
      cout << " illustrate  bool   true: ";

      //   cout ,   
      //     true  false
      cout << boolalpha;
      cout << illustrate << '\n';
   }

            .
        
,     .       bool 
        .
     cout,  
 noboolalpha:

   cout << boolalpha //    cout
          << illustrate
      << noboolalpha //    cout

     ,     .
            
 .       
,      (   
 ,       ),   hex, oct 
dec:

1080

   #include <iostream>

   int main()
   {
      int ival = 16;
      double dval = 16.0;

      cout << "ival: " << ival
             << "  oct: " << oct << ival << "\n";

      cout << "dval: " << dval
             << "  hex: " << hex << dval << "\n";

      cout << "ival: " << ival
             << "  dec: " << dec << ival << "\n";
   }

      :

   ival: 16  oct: 20
   dval: 16  hex: 16
   ival: 10  dec: 16

   ,   ,    ,      .
, 20    20    16? 
showbase         
 :

    0x      (  , 
        'x'  ,   
      uppercase,      nouppercase);
    0     ;
          .

       ,     showbase:

   #include <iostream>

   int main()
   {
      int ival = 16;
      double dval = 16.0;

      cout << showbase;

      cout << "ival: " << ival
             << "  oct: " << oct << ival << "\n";

      cout << "dval: " << dval
             << "  hex: " << hex << dval << "\n";

      cout << "ival: " << ival
             << "  dec: " << dec << ival << "\n";

      cout << noshowbase;
   }

1081

:

   ival: 16  oct: 020
   dval: 16  hex: 16
   ival: 0x10  dec: 16

    noshowbase   cout,   
   .
            6.  
    - precision(int)  
setprecision();      
 iomanip. precision()    . :

   #include <iostream>
   #include <iomanip>
   #include <math.h>

   int main()
   {
      cout << ": "
             << cout.precision() << endl
             << sqrt(2.0) << endl;

      cout.precision(12);

      cout << "\n: "
             << cout.precision() << endl
            << sqrt(2.0) << endl;

      cout << "\n: " << setprecision(3)
             << cout.precision() << endl
             << sqrt(2.0) << endl;

     return 0;
   }

          :

   : 6
   1.41421
   : 12
   1.41421356237
   : 3
   1.41

   ,  , ,  setprecision()  setw(), 
   iomanip:

   #include <iomanip>

     , setprecision()   :     
  ;     ,  

1082

.  ,   4  3.14159   3.142, 
  3   3.14.
        ,      0.
   :

   cout << 10.00

   

   10

     ,   showpoint:

   << noshowpoint << '\n';

    noshowpoint    .
             
.        scientific, 
       fixed:

   cout << ": " << scientific
          << 10.0
          << "  : " << fixed
      << 10.0 << '\n';

     :

   : 1.0e+01
     : 10

         'e'  'E',    
 uppercase,     'e'  nouppercase. ( uppercase
         .)
           (,
 ,     ).   :

   a bc
   d

    

1083

   char ch;
   while ( cin >> ch )
      // ...

    'a'  'd'   ,    
 .  noskipws    
:

   char ch;
   cin >> noskipws;
   while ( cin >> ch )
      // ...
  cin >> skipws;

      while    .    
,   cin   skipws.

     :

   cout << ",  : ";

    cout   .   ,  
  (.. ),       :

      .      
      ;
             flush, ends
      endl:

   cout << "hi!" << endl;

          unitbuf 
         ;
     ostream    (tied)   istream.  
     ostream   ,  istream    .

     cout    cin:

   cin.tie( &cout );

   

   cin >> ival;

1084

    cout.
        ostream      
istream.    ,   - tie()
 0:

   istream is;
   ostream new_os;

   // ...

   // tie()   
   ostream *old_tie = is.tie();

   is.tie( 0 ); //   
   is.tie( &new_os ); //   

   // ...

   is.tie( 0 ); //   

   is.tie( old_tie ); //   

       ,      
,    setw(). , 

   #include <iostream>
   #include <iomanip>

   int main()
   {
      int ival = 16;
      double dval = 3.14159;

      cout << "ival: " << setw(12) << ival << '\n'
             << "dval: " << setw(12) << dval << '\n';
   }

   :

   ival: 16
   dval: 3.14159

     setw()  , ,    
, setw()      ostream.
        ,    left
(  right     ).
     :

      16
   -   3


1085

   internal,      , 
   ,    .    
,     setfill(). 

   cout << setw(6) << setfill('%') << 100 << endl;

   :

   %%%100

    . 20.1     .

       20.1. 

	 	

	boolalpha 		 true  false  
	*noboolalpha 	 true  false  1  0
	Showbase 		 ,   
	*noshowbase 	    
	showpoint 		   
	*noshowpoint 	      ,   
				
	showpos 		 +   
	*noshowpos 		  +   

	 	

	*skipws 		     
	noskipws 		      
	uppercase 		 0X      
				E      
	*nouppercase 	 0x      
				e      
	*dec 			   
	hex 			   
	oct 			   

1086

	left 			     
	right 		     
	internal 		      
	*fixed 		       
	scientific 		       
	flush 		  ostream
	ends 			  ,    ostream
	endl 			   ,    ostream
	ws 			  
				//     #include <ionamip>
	setfill( ch) 	    ch
	Setprecision( n )         n
	setw( w ) 		       w
	setbase( b ) 	     b

	*     


                         20.10.   

    iostream  . ,    
 ostream      istream   
 . ,    :

   #include <iostream>
   #include <fstream>
   class Screen;

   extern istream& operator>>( istream&, const Screen& );
   extern void print( ostream& );

   ifstream inFile;

       ,  
 :

1087

   int main()
   {
      Screen myScreen;

     // :  ostream&
      print( cin >> myScreen );

      // :   >>
      inFile << ":  ";

    /      C++.   20
 iostream   ,     
        
  .         iostream,
      /.
