Skip to main contentCal State San Bernardino / [CNS] / [Comp Sci Dept] / [R J Botting] >> [CSci202] >> iomanip
[Index] [Schedule] [Syllabi] [Text] [Labs] [Projects] [Resources] [Search] [Contact] [Grading]
Notes: [01] [02] [03] [04] [05] [06] [07] [08] [09] [10] [11] [12] [13] [14] [15] [16] [17] [18] [19] [20]
Sun May 6 10:25:05 PDT 2007

Contents


    C++ Stream I/O

      Introduction

      This is a summary of the C++ Stream Input/Output Libraries that I extracted from the Gnu C++ Library.

      I've added some advice.

      This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.

      The #include files are in /usr/local/lib/g++-include:


      1. iostream.h -- normal Input/Output
      2. iomanip.h -- Manipulating formats and such
      3. fstream.h -- accessing files
      4. strstream.h -- treating strings as files

      The following sections give a rough picture of what is defined in these four libraries.

      iostream.h

        Convert numbers to C strings

      1. char* form(const char*, ...); //Use printf formating on ... items

        For NUMERIC=long|int|unsigned|long unsigned,

      2. char* dec(NUMERIC, int=0);// decimal format of ints,longs,....
      3. char* hex(NUMERIC, int=0);// octal format
      4. char* oct(NUMERIC, int=0);// hex format
      5. char* oct(int, int=0);
      6. char* oct(unsigned long, int=0);
      7. char* oct(unsigned int, int=0);

      8. char* chr(char ch, int width = 0); //Convert char to string
      9. char* str(const char* s, int width = 0);// Format string to width

        istream

        Class of input streams
      10. istream& ws(istream& ins);//skip white space

        ostream

        Output streams
      11. ostream& flush();// flush cout
      12. ostream& flush(ostream& outs);// send bufferout...
      13. ostream& endl(ostream& outs);//mark end of line
      14. ostream& ends(ostream& outs);//Mark end of stream(close it)

        Output Character:

      15. ostream& put(char c)// output a character to this stream
      16. ostream& put(unsigned char c) // output a character to this stream
      17. ostream& put(signed char c) { return put((char)c); }

        <<

      18. ostream& operator<<(char c);
      19. ostream& operator<<(unsigned char c);
      20. ostream& operator<<(signed char c) ;
      21. ostream& operator<<(const char *s);
      22. ostream& operator<<(const unsigned char *s)
      23. ostream& operator<<(const signed char *s)
      24. ostream& operator<<(const void *p);
      25. ostream& operator<<(int n);
      26. ostream& operator<<(unsigned int n);
      27. ostream& operator<<(long n);
      28. ostream& operator<<(unsigned long n);
      29. ostream& operator<<(long long n);
      30. ostream& operator<<(unsigned long long n);
      31. ostream& operator<<(short n)
      32. ostream& operator<<(unsigned short n)
      33. ostream& operator<<(double n);
      34. ostream& operator<<(float n)
      35. ostream& operator<<(__omanip func)
      36. ostream& operator<<(__manip func)
      37. ostream& operator<<(streambuf*)

        Input functions

      38. istream& get(char* ptr, int len, char delim = '\n');
      39. istream& get(unsigned char* ptr, int len, char delim = '\n')
      40. istream& get(char& c);
      41. istream& get(signed char& c) { return get((char&)c); }
      42. istream& get(signed char* ptr, int len, char delim = '\n')
      43. istream& get(unsigned char& c) { return get((char&)c); }

        Input string with delimeter and max length

      44. istream& getline(char* ptr, int len, char delim = '\n');
      45. istream& getline(unsigned char* ptr, int len, char delim = '\n')
      46. istream& getline(signed char* ptr, int len, char delim = '\n')

        Raw input of a buffer/Binary input

      47. istream& read(char *ptr, int n);
      48. istream& read(unsigned char *ptr, int n) { return read((char*)ptr, n); }
      49. istream& read(signed char *ptr, int n) { return read((char*)ptr, n); }
      50. istream& read(void *ptr, int n) { return read((char*)ptr, n); }

        Undo Input

      51. istream& unget(char ch) { return putback(ch); }

        Ignore input chars

      52. int skip(int i);

        >>

      53. istream& operator>>(char*);//UNSAFE unless you set width to space allocated in string
      54. istream& operator>>(unsigned char* p) { return operator>>((char*)p); }
      55. istream& operator>>(signed char*p) { return operator>>((char*)p); }
      56. istream& operator>>(char& c);// skips whitespace unless you unset skipws
      57. istream& operator>>(unsigned char& c) {return operator>>((char&)c);}
      58. istream& operator>>(signed char& c) {return operator>>((char&)c);}
      59. istream& operator>>(int&);
      60. istream& operator>>(long&);
      61. istream& operator>>(unsigned long long&);
      62. istream& operator>>(short&);
      63. istream& operator>>(unsigned int&);
      64. istream& operator>>(unsigned long&);
      65. istream& operator>>(unsigned short&);
      66. istream& operator>>(double&);
      67. istream& operator>>(streambuf*);

        Old C-style input

      68. istream& get(streambuf& sb, char delim = '\n');//does not skip whitespace
      69. istream& gets(char **s, char delim = '\n');//UNSAFE and INSECURE!
      70. istream& scan(const char *format ...);//The old scanf rides again

        iostream

      71. : public istream, public ostream{...}; IOStreams combine all the possibilities of istream and ostream

        Standard Input and output streams

      72. istream cin;
      73. ostream cout, cerr, clog;

        State of a stream:

      74. GOOD -- nothing has gone wrong yet
      75. FAIL -- something didn't work but the stream is OK
      76. BAD -- this stream has gone wrong
      77. EOF -- there is no more data to read here
      78. (unless FAIL occurred)

        Functions that extract state of stream

      79. int rdstate()//bit pattern describing state of stream

        Functions that test for exceptional conditions

      80. int good() const // True when GOOD
      81. int eof() const //False if input has failed
      82. int fail() const // true if failed state OR bad state
      83. int bad() const

        Read ahead

        The easiest way to read to EOF is to attempt to input characters and test for success at the same time
         while( cin >> character )
        because if the input fails th stream fails the test(it is (void*)0)

        More complex input may need a technique know as "reading ahead":

         	stream >> data; // read ahead
         	while(stream) // repeat until end or failure
         	{
         		...//consume data
         		stream >> data; // replace data by next item
         		...
         	}

        Resetting after Failing

      84. ios& clear()// set state to good
      85. ios& clear(states)//sets states

      . . . . . . . . . ( end of section iostream.h) <<Contents | End>>

      ios

      This is a class that is full of special constants used to control formatting. See the next section.

      Functions that change formatting

        Note: Some functions are also manipulators with different names. For example

      1. output_stream << setiosflags(whatever)

        is like

      2. output_stream.setf(whatever)

        and

      3. output_stream << resetiosflags(whatever)

        is like

      4. output_stream.unsetf(whatever)

        Control base of output and input

      5. ios& dec(ios& i)//set decimal output
      6. ios& hex(ios& i)//set hexadecimal output
      7. ios& oct(ios& i)//set octal outpu

        Control fill and width

      8. fill(int);//fill character (default is space)
      9. width(int);//width limit on field (input and output)

        Control via setting and unsetting flags

      10. setf(flags);//set falgs to be true
      11. unsetf(flags);//set flags to false

      12. setf(flags) OR unsetf(flags)
         Flags 		Meanings
         -----------------------------------------------------------
         ios::showpoint	show point in whole numbers
         ios::showbase	Indicate Base(0,0x,...)
         ios::showpos	Show +sign on positive
         ios::uppercase	EXABCDEF not exabcdef
         -----------------------------------------------------------

        Setting one bit in a group of bits actually means turning off the group and then turning one the correct bit on. There is a special version of the 'setf' function that does this:

      13. setf(selection,ingroup);//set to selection
         selection 	ios::ingroup	 	Meaning
         -----------------------------------------------------------
         ios::left	ios::adjustfield	left alignment
         ios::right	ios::adjustfield	right alignment
         ios::internal	ios::adjustfield	sign on left, digits right
        
        
         ios::dec		ios::basefield		decimals
         ios::hex		ios::basefield		hexadecimal
         ios::oct		ios::basefield		Octal
        
        
         ios::fixed	ios::floatfield		fixed form of floating point
         ios::scientific	ios::floatfield		force exponential format
         -----------------------------------------------------------

        However this 'setf' has no matching 'setiosflags' manipulator.

        [ formats.cc ]

        List of Format Flags in Library

        	ios::dec //		use decimals
        	ios::fixed //		no exponentials
        	ios::hex //		use hexadecimals
        	ios::internal //	sign on left, digits on right
        	ios::left //		left justified
        	ios::oct //		use octal
        	ios::right //		right justified
        	ios::scientific //	scientific notation
        	ios::showbase //	Show base (hex,octal,...)
        	ios::showpoint //	Always show a point
        	ios::showpos //		If positive still show sign
        	ios::skipws //		Skip whitespace on input
        	ios::stdio //		??
        	ios::unitbuf //		??
        	ios::uppercase //	Letters in hex are UPPERCASE

        List of Groups of fields

        	ios::adjustfield = ios::left | ios::right | ios::internal.
          ios::floatfield = ios::fixed | ios::scientific
          ios::basefield = ios::dec | ios::hex | ios::octal

        To turn on one bit in s group you can use ostream . setf(ios::bit, ios::ingroup); or ostream << resetiosflags(ios::ingroup)<<setiosflags(ios::bit)...

        iomanip.h

        This library automatically #includes <iostream.h>

        Manipulators are used in one of two ways:

      14. input_stream >> input_manipulator >>...
      15. output_stream << output_manipulator>>...

        They duplicate the member functions like setf and fill.

      16. setbase( int ) // base used to represent number
      17. setfill( int ) // Character used to fill non-digits in number
      18. setprecision( int ) //How many decimals after the point

        resetiosflags( ios::fmtflags ) // reset various properties setiosflags( ios::fmtflags ) // set various properties

        To turn on one bit in s group you can use ostream << resetiosflags(ios::ingroup)<<setiosflags(ios::bit)...

      19. setw( int ) //How many characters for the data

        The setw(W) manipulator is unusual in two ways. Firstly it is the only one above that effects the next transfer only. Secondly, it is used for both istreams and ostreams.

        [ giomanip.cc ]

        Do-it-yourself Manipulators

        Simple manipulators without arguments are very easy to define and can make many programs easier to both read and write.
         // Output manipulator example - Part 1
         ostream& left(ostream& out) //set left justified
         {	out.setf(ios::left, ios::adjustfield);
         	return out;
         }
         ostream& right(ostream& out) //set right justified
         {	out.setf(ios::right, ios::adjustfield);
         	return out;
         }
        A function that takes a reference to an istream and returns one as well can be used as an input manipulator. Similarly the name of a function that is given a ref to an ostream and returns a ref to an ostream is treated as an ostream manipulator.

         // Output manipulator example - Part 2
         ostream& dollars(ostream& out) //set check protected monetary formatting
         {
          	return out << '$' << setfill('*') <<setw(10)
         	<< setprecision(2) << setiosflags(ios::fixed | ios:: showpoint);
         }
         ...
         	cout << dollars << example << endl;
         	cout << left << dollars << example << endl;
         	cout << right << dollars << example << endl;

        Setting up manipulators that have arguments is more complicated because functions that have arbitrary arguments are not recognised as iomanipulators by '<<' and '>>'. See see << and see >> above.

        The technique is to define a class of objects with a constructor that has the arguments that you want that returns a function with the correct argument that has access to values of the arguments as data members of the class. Believe it or not!

      fstream.h

        The following is straight from the library....

        fstreambase

      1. : public ios

        fstreambase is used as a base for ifstream, ofstream and fstream. These are effectively the result of combining the the possibilities of handling files (fstreambase) with the matching stream class(istream, ostream, iostream respectively).

        Constructors

      2. fstreambase();
      3. fstreambase(int fd);
      4. fstreambase(const char *name, int mode, int prot=0664);

      5. void close();
      6. filebuf* rdbuf() const ;
      7. void open(const char *name, int mode, int prot=0664);
      8. int is_open() const ;
      9. void setbuf(char *ptr, int len) ;

        ifstream

      10. : public fstreambase, public istream

        Constructors

      11. ifstream() : fstreambase() { }
      12. ifstream(int fd) : fstreambase(fd) { } ifstream(const char *name, int mode=ios::in, int prot=0664)
      13. : fstreambase(name, mode, prot) { }

        void open(const char *name, int mode=ios::in, int prot=0664);

        ofstream

      14. : public fstreambase, public ostream

        Constructors

      15. ofstream() : fstreambase() { }
      16. ofstream(int fd) : fstreambase(fd) { } ofstream(const char *name, int mode=ios::out, int prot=0664) : fstreambase(name, mode, prot) { }

        void open(const char *name, int mode=ios::out, int prot=0664) ;

        fstream

      17. : public fstreambase, public iostream

        Constructors

      18. fstream() : fstreambase() { }
      19. fstream(int fd) : fstreambase(fd) { }
      20. fstream(const char *name, int mode, int prot=0664): fstreambase(name, mode, prot) { }

      21. void open(const char *name, int mode, int prot=0664) ;

      strstream.h

        #include <iostream.h>

        strstreambuf

        Many constructors:
      1. strstreambuf() ;
      2. strstreambuf(int initial_size) ;
      3. strstreambuf(void *(*alloc)(_G_size_t), void (*free)(void*)) ;
      4. strstreambuf(char *ptr, int size, char *pstart = NULL) ;
      5. strstreambuf(unsigned char *ptr, int size, unsigned char *pstart = NULL) ;
      6. strstreambuf(const char *ptr, int size) ;
      7. strstreambuf(const unsigned char *ptr, int size) ;
      8. ~strstreambuf();

      9. int frozen() ;
      10. void freeze(int n=1) ;
      11. _G_size_t pcount();
      12. char *str(); streampos seekoff(streamoff, _seek_dir, int mode=ios::in|ios::out);

        strstreambase

      13. : public ios
      14. strstreambuf* rdbuf() ;

        istrstream

      15. : public strstreambase, public istream
      16. istrstream(const char*, int=0);

        ostrstream

      17. : public strstreambase, public ostream
      18. ostrstream(); ostrstream(char *cp, int n, int mode=ios::out) :strstreambase(cp,n,mode){}

      19. _G_size_t pcount() ;
      20. char *str() ;
      21. void freeze(int n = 1) ;
      22. int frozen() ;

        strstream

      23. : public strstreambase, public iostream
      24. public:
      25. strstream() : strstreambase() ; strstream(char *cp, int n, int mode=ios::out) :strstreambase(cp,n,mode){}
      26. _G_size_t pcount() ;
      27. char *str() ;
      28. void freeze(int n = 1) ;
      29. int frozen() ; };

    Abreviations

  1. TBA::="To Be Announced", something I have to do.
  2. TBD::="To Be Done", something you have to do.
  3. Dia::="A free Open Source Diagramming tool for Linux, Windoze, etc. ".

End