home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 7 / Apprentice-Release7.iso / Utilities / Programming / C Reference Card 3.0 / C Reference Card / C Reference Card.rsrc / TEXT_415_15.txt < prev    next >
Encoding:
Text File  |  1997-07-17  |  8.7 KB  |  308 lines

  1. I/O STREAMS : objects and manipulators, examples
  2. _________________________________________________________________________
  3.  
  4.  
  5. C++ uses a set of input/output (I/O) stream class libraries for input and output.  Objects defined in these classes can be overloaded and extended just as any other C++ objects.  Although you may still use the <stdio.h> function calls in the ANSI C library, you should probably get use to using streams.  The following figure is the class hierarchy for C++ I/O classes and a brief description of the class names:
  6.  
  7.                                   ios
  8.                                    |
  9.                               ___________
  10.                              |           |
  11.                           istream     ostream
  12.                              |           |
  13.                         __________   ____________
  14.                        |          | |            |
  15.                    ifstream    iostream      ofstream
  16.                                    |
  17.                                 fstream
  18.  
  19.  
  20. Generally, you'll be using the iostream class for standard I/O, and the fstream class for file I/O.  In addition, the iomanip.h header file is frequently used and contains parameterized stream manipulators which are function-like calls which are used to change various I/O settings.
  21.  
  22. The following snippet shows how to use the basics of using C++ I/O streams.  The insert operator '<<' and extraction operator '>>' are used to send and get data from the screen and keyboard.
  23.  
  24.   // io.cp
  25.   #include <iostream.h>
  26.   #include <iomanip.h>
  27.     
  28.   main()
  29.   {
  30.     int   i;
  31.     float f;
  32.     char  c;
  33.     
  34.     cout << "Enter an integer: ";
  35.     cin >> i;
  36.     cout << "Enter a float: ";
  37.     cin >> f;
  38.     cout << "Enter a character: ";
  39.     cin >> c;
  40.     
  41.     cout << endl;
  42.     cout << "Default formats" << endl;
  43.     cout << i << endl;
  44.     cout << f << endl;
  45.     cout << c << endl;
  46.     
  47.     cout << endl << "Other formats" << endl;
  48.     cout << hex << i << endl;
  49.     cout << setprecision(2) << f << endl;
  50.     cout << setiosflags( ios::scientific ) << f << endl;
  51.  
  52.     return 0;
  53.   }
  54.   // end io.cp
  55.  
  56.  
  57.  
  58. INPUT STREAMS
  59. _________________________________________________________________________
  60.  
  61. Predefined input stream is cin (standard input).  The >> operator is overloaded for input streams.
  62.  
  63. GCOUNT
  64. int gcount()
  65. Returns number of characters read by last unformatted read.
  66.  
  67. GET
  68. int get()
  69. istream &get( char & )
  70. istream &get( unsigned char & )
  71. istream &get( char *buf, int limit, char delim='\n' )
  72. istream &get( unsigned char *buf, int limit, char delim='\n' )
  73. Gets single character or series of characters (until end-of-file is reached).  Delimiter, if read, is not included in characters read and is left in stream.
  74.  
  75. GETLINE
  76. istream &getline( char *buf, int limit, char delim='\n' )
  77. istream &getline( unsigned char *buf, int limit, char delim='\n' )
  78. Reads characters until delimiter is read or limit-1 characters are read (or until end-of-file).  The delimiter, if read, is included in character sequence.
  79.  
  80. IGNORE
  81. istream &ignore( int limit=1, int delim=EOF )
  82. Discards number of characters or until delimiter is encountered.
  83.  
  84. PEEK
  85. int peek()
  86. Look at next character to be read without reading it.
  87.  
  88. PUTBACK
  89. istream &putback( char )
  90. Puts character back onto stream.  Can safely put one character back between successive calls to get().
  91.  
  92. READ
  93. istream &read( char *buf, int count )
  94. istream &read( unsigned char *buf, int count )
  95. Reads a string of characters from stream.  Sets "failbit" if end-of-file encountered.
  96.  
  97. SEEKG
  98. istream &seekg( streampos, seek_dir=ios::beg )
  99. Moves position of "get" pointer.  The type streampos is an alias for type long.
  100.  
  101. TELLG
  102. streampos tellg()
  103. Returns current position of "get" pointer in file stream.
  104.  
  105. WS
  106. istream &ws( istream & )
  107. Discards whitespace characters from stream.
  108.  
  109.  
  110.  
  111. OUTPUT STREAMS
  112. _________________________________________________________________________
  113.  
  114. Predefined output streams are cout (standard output) and cerr (standard error).  The << operator is overloaded for output streams.
  115.  
  116. ENDL
  117. ostream &endl( ostream & )
  118. Writes '\n' and flushes stream.
  119.   Example:
  120.     cout << endl;
  121.  
  122. FLUSH
  123. ostream &flush()
  124. ostream &flush( ostream & )
  125. Flushes stream buffer.
  126.   Examples: 
  127.     cout.flush();
  128.     cout << flush;
  129.  
  130. PUT
  131. ostream &put( char )
  132. Writes single character to stream.
  133.  
  134. SEEKP
  135. ostream &seekp( int &streampos, seek_dir=ios::beg )
  136. Moves position of "put" pointer.  seek_dir can be beginning (ios::beg), current (ios::cur), or end of the file (ios::end).
  137.  
  138. TELLP
  139. streampos tellp()
  140. Returns current "put" pointer.
  141.   Example:
  142.     streampos place = theFile.tellp();
  143.  
  144. WRITE
  145. ostream &write( const char *buf, int count )
  146. ostream &write( const unsigned char *buf, int count )
  147. Writes specified number of characters to stream.
  148.  
  149.  
  150.  
  151. FILE I/O
  152. _________________________________________________________________________
  153.  
  154. Reading and writing to files is achieved by associating a file stream with a variable with statements like:
  155.  
  156.   ifstream inputFile( "myInputFile.txt" );
  157.   if( !inputFile )
  158.     doInputError();
  159.  
  160.   ofstream outputFile( "myOutputFile.txt" );
  161.   if( !outputFile )
  162.     doOutputError();
  163.  
  164. OPEN
  165. void open( char *name, int mode=ios::out, int prot=filebuf::openprot )
  166. Protection mode is operating-system dependent.  Values for "mode" are:
  167.   ios::app        Data appended to file (implies ios::out).
  168.   ios::ate        Data appended to file (does not imply ios::out).
  169.   ios::in         File is opened for input.
  170.   ios::out        File opened for output.
  171.   ios::trunc      Discard previous contents of file.
  172.   ios::nocreate   If file does not exist, open() will fail.
  173.   ios::noreplace  If file exists, open() will fail.
  174.   Example:
  175.     ifstream inputFile;
  176.     inputFile.open( "myInputFile.txt" );
  177.  
  178.  
  179.  
  180. ERROR STATES
  181. _________________________________________________________________________
  182.  
  183. Error states are maintained for every stream.  These states are contained in the 'eofbit', 'failbit', and 'badbit'.
  184.  
  185. BAD
  186. int bad()
  187. Returns true if some operation on stream failed (recovery unlikely).
  188.  
  189. CLEAR
  190. void clear( int state )
  191. Sets error state of stream.
  192.  
  193. EOF
  194. int eof()
  195. Returns true if stream encounters end of file.
  196.  
  197. FAIL
  198. int fail()
  199. Returns true if some operation on stream failed.  Stream is useable once the condition is cleared.
  200.  
  201. GOOD
  202. int good()
  203. Returns true if eof(), bad(), and fail() are false.
  204.  
  205. OPERATOR
  206. int operator!()
  207. operator void*()
  208. Overloaded operators return true/false if failbit or badbit is set.
  209.  
  210. RDSTATE
  211. int rdstate()
  212. Returns current error state.
  213.  
  214.  
  215.  
  216. FORMATTING
  217. _________________________________________________________________________
  218.  
  219. Many format statements require the inclusion of the standard <iomanip.h> header file.  These statements are identified as such.  The following are a list of format flags and bitfields used by streams:
  220.  
  221.   skipws       Skips whitespace on input.
  222.  
  223.   left,        Sets justification within field.
  224.   right,
  225.   internal
  226.  
  227.   dec,         Set base for insertion/extraction of integral types.
  228.   oct,         Comprise static member ios::basefield.
  229.   hex
  230.  
  231.   showbase     Display 0 before octal and 0x before hexadecimal values.
  232.  
  233.   showpoint    Show decimal point and trailing zeros.
  234.  
  235.   showpos      Insert + sign before positive values.
  236.  
  237.   scientific,  Sets floating point notation.  Comprise static member
  238.   fixed        ios::floatfield.
  239.  
  240.   uppercase    Use uppercase for hexadecimal X and exponential E.
  241.  
  242. The following is a list of format statements.  Those statements which have a return type of ios& are stream manipulators (placed into stream with << and >> operators).
  243.  
  244. DEC
  245. ios& dec( ios & )
  246. Sets decimal base.
  247.  
  248. FILL
  249. char fill()
  250. char fill( char )
  251. Sets fill character (if provided), returns previous fill character.
  252.  
  253. FLAGS
  254. long flags()
  255. long flags( long )
  256. Returns current flags, or if flags provided returns previous flags.
  257.  
  258. HEX
  259. ios &hex( ios & )
  260. Sets hexidecimal base.
  261.  
  262. OCT
  263. ios &oct( ios & )
  264. Sets octal base.
  265.  
  266. PRECISION
  267. int precision()
  268. int precision( int )
  269. Sets number of significant digits (if provided), returns current/previous value.
  270.  
  271. RESETIOSFLAGS
  272. ios &resetiosflags( long ) -- requires <iomanip.h>
  273. Turns off specified flags.
  274.  
  275. SETBASE
  276. ios &setbase( int ) -- requires <iomanip.h>
  277. Sets numerical base based on integer provided.
  278.  
  279. SETF
  280. long setf( long bitFlags )
  281. long setf( long bitFlags, long bitField )
  282. Clears bitField and sets format flags, returns previous flags.
  283.  
  284. SETFILL
  285. ostream &setfill( char ) -- requires <iomanip.h>
  286. Sets fill character.
  287.  
  288. SETIOSFLAGS
  289. ios &setiosflags( long ) -- requires <iomanip.h>
  290. Sets format flags.
  291.  
  292. SETPRECISION
  293. ios &setprecision( int ) -- requires <iomanip.h>
  294. Sets number of significant digits.
  295.  
  296. SETW
  297. ios &setw( int size ) -- requires <iomanip.h>
  298. Sets size (width) of line buffer.
  299.  
  300. UNSETF
  301. long unsetf( long )
  302. Turns off specified flags and returns previous flags.
  303.  
  304. WIDTH
  305. int width()
  306. int width( int minimum )
  307. Sets minimum field width if provided (zero = no minimum).  Returns current width.  Reset to zero after each insertion/extraction.
  308.