[Skip Navigation] [CSUSB] / [CNS] / [Comp Sci & Eng] / [R J Botting] / [CSci202] / iomanip
[Text Version] [Syllabus] [Schedule] [Glossary] [Resources] [Grading] [Contact] [Question] [Search ]
Notes: [01] [02] [03] [04] [05] [06] [07] [08] [09] [10] [11] [12] [13] [14] [15] [16] [17] [18] [19] [20]
Labs: [01] [02] [03] [04] [05] [06] [07] [08] [09] [10]
Mon Apr 19 16:59:48 PDT 2010

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 some years ago.

      I've added some advice.

      The #include library are


      1. iostream -- Combines istream and ostream and declares cib, cout,...
      2. istream -- normal Input
      3. ostream -- normal Output
      4. iomanip -- Manipulating formats and such
      5. fstream -- accessing files as streams
      6. sstream -- treating strings as streams -- stringstreams

      These all place their declarations into namesapce std and so you will need

       		using namespace std;
      or
       		using std::whatever
      (whatever is an object/function defined below) to use them as shown below.

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

      iostream

        Convert numbers to C strings

      1. char* form(const char*, ...); //Use the old 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
      10. char* str(const string s);// Extract char* from string

        istream

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

        ostream

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

        Output a Character:

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

        <<

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

        Input functions

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

        Input string with delimeter and max length

      46. istream& getline(string s, char delim = '\n');
      47. istream& getline(string s, int len, char delim = '\n');
      48. istream& getline(char* ptr, int len, char delim = '\n');
      49. istream& getline(unsigned char* ptr, int len, char delim = '\n')
      50. istream& getline(signed char* ptr, int len, char delim = '\n')

        Raw input of a buffer/Binary input

      51. istream& read(char *ptr, int n);
      52. istream& read(unsigned char *ptr, int n) { return read((char*)ptr, n); }
      53. istream& read(signed char *ptr, int n) { return read((char*)ptr, n); }
      54. istream& read(void *ptr, int n) { return read((char*)ptr, n); }

        Undo Input

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

        Ignore input chars

      56. int skip(int i);

        >>

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

        Old C-style input

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

        iostream

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

        Standard Input and output streams

      77. istream cin;
      78. ostream cout, cerr, clog;

        State of a stream:

      79. stream_state::={GOOD, FAIL, BAD, EOF}.
      80. GOOD::stream_state= nothing has gone wrong yet.
      81. FAIL::stream_state= something didn't work but the stream is OK.
      82. BAD::stream_state= this stream has gone wrong.
      83. EOF::stream_state= there is no more data to read here (unless FAIL occurred).

        Functions that extract state of stream

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

        Functions that test for exceptional conditions

      85. int good() const // True when GOOD
      86. int eof() const //False if input has failed
      87. int fail() const // true if failed state OR bad state
      88. int bad() const

        Read ahead

        In C++ you only find out that data does not exist by attempting to read it and failing. So you need to (1) get same data, and (2) test it. But the following
         while( ! cin.eof() ) { cin>>data; consume the data }
        does not work because it (1) tests the stream and then (2) gets the data. At the end of the stream the loop attempts to get the nonexistent data, fails, processes the previous data (!), and then tries again. Not what we want!

        The easiest way to read to EOF is to attempt to input characters and test for success at the same time:

         while( cin >> character ){ consume the character }
        This works because when the input fails, the stream returns a fals bool value(it is (void*)0).

        More complex input usually needs 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

      89. ios& clear()// set state to good
      90. ios& clear(states)//sets states

      . . . . . . . . . ( end of section iostream) <<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.cpp ]

        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

          This library automatically #includes <iostream>. It defines a large number of operations that can be applied to a stream. Manipulators are used in one of two ways:
        1. input_stream >> input_manipulator >>...
        2. output_stream << output_manipulator <<...

          They duplicate the member functions of stream like setf and fill.

        3. setbase( int )::iomanip= base used to represent number.
        4. setfill( int )::iomanip= Character used to fill non-digits in number.
        5. setprecision( int )::iomanip=How many decimals after the point.

        6. resetiosflags( formatflags )::iomanip= reset various properties.
        7. setiosflags( formatflags )::iomanip= set various properties.

          Note: formatflags is part of namespace ios

           		ios::formatflags

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

        8. setw( int )::iomanip=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.cpp ]

        9. left::iomanip= output left aligned -- strings and numerics.
        10. right::iomanip= output right aligned -- strings and numerics.
        11. hex::iomanip= hexadecimal numbers.
        12. oct::iomanip=output numbers.
        13. dec::iomanip=decimal numbers.
        14. boolalpha::iomanip=bool converted to T and F.
        15. showpoint::iomanip=show point in whole numbers.
        16. noshowpoint::iomanip=don't show point in whole numbers.
        17. showbase::iomanip=Indicate Base(0,0x,...).
        18. noshowbase::iomanip=Don't Indicate Base(0,0x,...).
        19. showpos::iomanip=Show +sign on positive.
        20. noshowpos::iomanip=Don't Show +sign on positive.
        21. uppercase::iomanip=EXABCDEF not exabcdef.
        22. nouppercase::iomanip=exabcdef not EXABCDEF.

        . . . . . . . . . ( end of section iomanip) <<Contents | End>>

        Do-it-yourself Manipulators

        Simple manipulators without arguments are very easy to define and can make many programs easier to both read and write. 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

        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) ;

      stringstreams and sstream

        #include <iostream>

        stringstreambase

      1. : public ios
      2. stringstreambuf* rdbuf() ;

        istringstream

      3. : public stringstreambase, public istream
      4. istringstream(const char*, int=0);

        ostringstream

      5. : public stringstreambase, public ostream
      6. ostringstream(); ostringstream(char *cp, int n, int mode=ios::out) :stringstreambase(cp,n,mode){}

      7. _G_size_t pcount() ;
      8. char *str() ;
      9. void freeze(int n = 1) ;
      10. int frozen() ;

        stringstream

      11. : public stringstreambase, public iostream
      12. public:
      13. stringstream() : stringstreambase() ; stringstream(char *cp, int n, int mode=ios::out) :stringstreambase(cp,n,mode){}
      14. _G_size_t pcount() ;
      15. char *str() ;
      16. void freeze(int n = 1) ;
      17. int frozen() ; };

    Abbreviations

  1. Algorithm::=A precise description of a series of steps to attain a goal, [ Algorithm ] (Wikipedia).
  2. class::="A description of a set of similar objects that have similar data plus the functions needed to manipulate the data".
  3. Data_Structure::=A small data base.
  4. Function::programming=A selfcontained and named piece of program that knows how to do something.
  5. Gnu::="Gnu's Not Unix", a long running open source project that supplies a very popular and free C++ compiler.
  6. KDE::="Kommon Desktop Environment".
  7. object::="A little bit of knowledge -- some data and some know how", and instance of a class".
  8. OOP::="Object-Oriented Programming", Current paradigm for programming.
  9. Semantics::=Rules determining the meaning of correct statements in a language.
  10. SP::="Structured Programming", a previous paradigm for programming.
  11. STL::="The standard C++ library of classes and functions" -- also called the "Standard Template Library" because many of the classes and functions will work with any kind of data.
  12. Syntax::=The rules determining the correctness and structure of statements in a language, grammar.
  13. Q::software="A program I wrote to make software easier to develop",
  14. TBA::="To Be Announced", something I should do.
  15. TBD::="To Be Done", something you have to do.
  16. UML::="Unified Modeling Language".
  17. void::C++Keyword="Indicates a function that has no return".

End