This section describes the operators that are common to both input and output. #include <iostream.h> class ios enum enum tabexp}; enum /* Format control flags */ skipws=01, }; static const long basefield; /* dec | oct | hex */ static const long adjustfield; /* left | right | internal */ static const long floatfield; /* scientific | fixed */ public: ios(streambuf*);
protected: ios(); init(streambuf*); private: ios(ios&);void }; /* Manipulators */
| |||||||||
The stream classes derived from class ios provide a high level interface that supportstransferring formatted and unformatted information into and out of streambuf Several enumerations are declared in class ios, open_mode, io_state, seek_dir, and In the following descriptions, assume:
Constructors and assignmentios(streambuf * sb) The streambuf denoted by sb becomes the streambuf associated with the constructed ios. If sb is null, the effect is undefined. ios(ios& sr) Copying of ioss is not well-defined in general, therefore the constructor and assignment operators are private so that the compiler complains about attempts to copy ios objects. Copying pointers to iostreams is usually what is required. ios() Because class ios is now inherited as a virtual base class, a constructor with no arguments must be used. This constructor is declared protected. Therefore ios::init(streambuf*) is declared protected and must be used for initialization of derived classes. Error statesAn ios has an internal error state (which is a collection of the bits declared as io_states). Members related to the error state are: int i=s.rdstate() Returns the current error state. s.clear(int i) Stores i as the error state. If i is zero, this clears all bits. To set a bit without clearing previously set bits requires something like s.clear(ios::badbit|s.rdstate()). int i=s.good() Returns non-zero if the error state has no bits set, zero otherwise. int i=s.eof() Returns non-zero if eofbit is set in the error state, zero otherwise. Normally this bit is set when an end-of-file has been encountered during an extraction. int i=s.fail() Returns non-zero if either badbit or failbit is set in the error state, zero otherwise. int i=s.bad() Returns non-zero if badbit is set in the error state, zero otherwise. This usually indicates that some operation on s.rdbuf() has failed, a severe error, from which recovery is probably impossible. That is, it is probably impossible to continue I/O operations on s. OperatorsTwo operators are defined to allow convenient checking of the error state of an ios object: operator!() and operator void*() or operator const void*() const. The latter converts an ios to a pointer so that it can be compared to zero. The conversion returns0 if failbit or badbit is set in the error state, and returns a pointer value otherwise. This pointer is not meant to be used. This allows you to write expressions such as:
The ! operator returns non-zero if failbit or badbit is set in the error state, which allows expressions such as the following to be used:
FormattingAn ios has a format state that is used by input and output operations to control the details of formatting operations. The format state components may be set and examined arbitrarily by user code. Most formatting details are controlled by using the flags(), setf(), and unsetf() functions to set the following flags, which are declared in an enumeration in class ios. Three other components of the format state are controlled separately with the functions fill(), width(), and precision(). skipws If skipws is set, whitespace is skipped on input. This applies to scalar extractions. left These flags control the padding of a value. When left is set, the value is left-adjusted,that is, the fill character is added after the value. When right is set, the value is right adjusted, that is, the fill character is added before the value. When internal is set, the fill character is added after any leading sign or base indication, but before the value.Right-adjustment is the default if none of these flags is set. These fields are dec These flags control the conversion base of an integer value. The conversion base is10 (decimal) if dec is set, but if oct or hex is set, conversions are done in octal or hexadecimal, respectively. If none of these is set, insertions are in decimal, but extractions are interpreted according to the C++ lexical conventions for integral constants. These fields are collectively identified by the static member, ios::basefield.The manipulators hex, dec, and oct, can also be used to set the conversion base, see "Built-in Manipulators" below. showbase If showbase is set, insertions are converted to an external form that can be read according to the C++ lexical conventions for integral constants. This means octals are preceded by the character ’0’, and hexadecimals are preceded by the string ’0x’(cf. uppercase). showbase is unset by default. showpos If showpos is set, then a plus character ’+’ is inserted into a decimal conversion of a positive integral value. uppercase If uppercase is set, then an uppercase X is used for hexadecimal output when showbase is set, or an uppercase E is used to print floating point numbers in scientific notation. showpoint If showpoint is set, trailing zeros and decimal points appear in the result of a floatingpoint conversion. scientific These flags control the format to which a floating point value is converted for insertion into a stream.
scientific and fixed are collectively identified by the static member, ios::floatfield. unitbuf When set, a flush is performed by ostream::osfx() after each insertion. Unit buffering provides a compromise between buffered output and unbuffered output. Performanceis better under unit buffering than unbuffered output, which makes a C runtime stdio When set, stdout and stderr are flushed by ostream::osfx() after each insertion. The following functions use and set the format flags and variables. char oc=s.fill(char c) Sets the "fill character" format state variable to c and returns the previous value. c isused as the padding character, if necessary (see width(), below). The default fill or padding character is a space. The positioning of the fill character is determined by the right, left, internal flags, see above. A parameterized manipulator, setfill, is also available for setting the fill character, see manip. Note The "fill character" has no effect on input. char c=s.fill() Returns the "fill character" format state variable. long l=s.flags() Returns the current format flags. long l=s.flags(long f) Resets all the format flags to those specified in f and returns the previous settings. int oi=s.precision(int i) Sets the "precision" format state variable to i and returns the previous value. This variable controls the number of significant digits inserted by the floating point inserter. The default is 6. A parameterized manipulator, setprecision is also availablefor setting the precision, see manip. int i=s.precision() Returns the "precision" format state variable. long l=s.setf(long b) Turns on in s the format flags marked in b and returns the previous settings. All otherflags are left unchanged. A parameterized manipulator, setiosflags performs the samefunction, see manip. long l=s.setf(long b, long f) Resets in s only the format flags specified by f to the settings marked in b, and returns the previous settings. That is, the format flags specified by f are cleared in s,then reset to be those marked in b. For example, to change the conversion base in s to be hex, you could write:
Any previous settings to oct or dec will be cleared by this. ios::basefield specifies the conversion base bits as candidates for change, and ios::hex specifies the new value. s.setf(0, f) clears all the bits specified by f, as does a parameterized manipulator, resetiosflags (see manip). long l=s.unsetf(long b) Unsets in s the bits set in b and returns the previous settings. int oi=s.width(int i) Sets the "field width" format variable to i and returns the previous value. This has two different meanings for either output or input streams:
A parameterized manipulator, setw is also available for setting the width (see manip). int i=s.width() Returns the "field width" format variable. User-defined format flagsSeveral functions are provided to allow users to derive classes from the base class iosthat require additional format flags or variables. The two static member functions ios::xalloc and ios::bitalloc, allow several such classes to be used together without interference. long b=ios::bitalloc() Returns a long with a single, previously unallocated, bit set. This allows users who need an additional flag to acquire one, and then pass it as an argument to ios::setf(), for example. int i=ios::xalloc() Returns a previously unused index into an array of words available for use as format state variables by derived classes. long & l=s.iword(int i) When i is an index allocated by ios::xalloc, iword() returns a reference to the ith user-defined word. void*& vp=s.pword(int i) When i is an index allocated by ios::xalloc, pword() returns a reference to the ith user-defined word. pword() is similar to iword, except that it has a different return type. Other membersstreambuf* sb=s.rdbuf() Returns a pointer to the streambuf associated with s when s was constructed. static void ios::sync_with_stdio() Solves problems that arise when mixing stdio and iostreams. The first time it is calledit resets the standard iostreams (cin, cout, cerr, clog; see iosintro to be streams using stdiobufs. After that input and output using these streams may be mixed with input and output using the corresponding FILEs (stdin, stdout, and stderr) and is properly synchronized. sync_with_stdio() makes cout and cerr unit buffered (see ios::unitbuf ans ios::stdio above). Invoking sync_with_stdio() degrades performance. Note Unit buffering for standard input/output files under BS2000 causes each read or written unit to close the current record and start reading or writing for the next record. ostream * oosp=s.tie(ostream * osp) Sets the "tie" variable to osp, and returns its previous value. This variable supports ostream * osp=s.tie() Note In the C runtime system, text output files are flushed before stdin (SYSDTA) is read.iostream::tie affects how the C++ buffer contents are passed to the C runtime system. Information passing from the C runtime system buffer to the file is not affected by the value of the tie variable. Built-in manipulatorsSome convenient manipulators (functions that take an ios&, an istream&, or an ostream& and return their argument, (see manip)) are: sr<<dec These set the conversion base format flag to 10. sr<<hex These set the conversion base format flag to 16. sr<<oct These set the conversion base format flag to 8. sr>>ws sr<<endl sr<<ends Ends a string by inserting a null(0) character. See ostream. sr<<flush Flushes sr. See ostream. Several parameterized manipulators that operate on ios objects are described in manip: setbase, setw, setfill, setprecision, setiosflags, and resetiosflags. The streambuf associated with an ios can be manipulated by other methods than through the ios. For example, characters can be stored in a queuelike streambuf through an ostream while they are being fetched through an istream, or for efficiency,some part of a program may choose to do streambuf operations directly rather than through the ios. In most cases the program does not have to worry about this possibility, because an ios never saves information about the internal state of a streambuf. For example, if the streambuf is repositioned between extraction operationsthe extraction (input) proceeds normally. | |||||||||
EXAMPLE | The following program uses some data members of class ios to change the output format of both integers and doubles on cout: #include <iostream.h> #include <math.h> void someoutput() { int i; const int N = 12; for (i = 1; i < N; i += 2) { cout << "\t" << i << " " << pow( (double) i, (double) i) << endl; } cout << "\n"; } int main() { cout << "Default format :\n"; someoutput(); /* show default formats for integers and doubles */ cout.setf( ios::fixed, ios::floatfield); /* set the output format for floats and doubles to fixed*/ cout << "The output format for floats and doubles is fixed :\n"; someoutput(); cout.setf( ios::oct, ios::basefield); /* set the output format for integers to octal */ cout << "The output format for integers is octal :\n"; someoutput(); return 0; } The result of executing the program is: Default format : 1 1 3 27 5 3125 7 823543 9 3.8742e+08 11 2.85312e+11 The output format for floats and doubles is fixed : 1 1.000000 3 27.000000 5 3125.000000 7 823543.000000 9 387420488.999998 11 285311670610.995117 The output format for integers is octal : 1 1.000000 3 27.000000 5 3125.000000 7 823543.000000 11 387420488.999998 13 285311670610.995117 % CCM0998 CPU time used: 0.0066 seconds Note The precision of these results depends on the machine used. | ||||||||
BUGS | The iostream package does not allow copying of streams. However, objects of type istream_withassign, ostream_withassign, and iostream_withassign can be assigned to. | ||||||||
SEE ALSO | |||||||||