Your Browser is not longer supported

Please use Google Chrome, Mozilla Firefox or Microsoft Edge to view the page correctly
Loading...

{{viewport.spaceProperty.prod}}

ios Base class for input/output


This section describes the operators that are common to both input and output.


#include <iostream.h>

class ios
{
public

enum io_state {goodbit=0, eofbit, failbit, badbit};

enum open_mode {in, out, ate, app, trunc, nocreate, noreplace,

 tabexp};

enum seek_dir {beg, cur, end};

/* Format control flags */
enum
{

skipws=01,
left=02, right=04, internal=010,
dec=020, oct=040, hex=0100,
showbase=0200, showpoint=0400,
uppercase=01000, showpos=02000,
scientific=04000, fixed=010000,
unitbuf=020000, stdio=040000

};

static const long basefield;

/* dec | oct | hex */

static const long adjustfield;

/* left | right | internal */

static const long floatfield;

/* scientific | fixed */

public:

ios(streambuf*);
virtual ˜ios();

int
static long
void
int
int
char

bad() const;
bitalloc();
clear(int state=0);
eof() const;
fail() const;
fill() const;

char
long
long
int
long&
int

fill(char);
flags() const;
flags(long);
good() const;
iword(int);
operator!() const;
operator void*();
operator const void*() const;

int
int
void* &
streambuf*
int
long
long
static void
ostream*
ostream*
long
int
int
static int

precision() const;
precision(int);
pword(int);
rdbuf();
rdstate() const;
setf(long setbits, long field);
setf(long);
sync_with_stdio();
tie();
tie(ostream*);
unsetf(long);
width() const;
width(int);
xalloc();

protected:

ios();

init(streambuf*);

private:

ios(ios&);void operator=(ios&);

};

/* Manipulators */

ios&
ios&
ios&
ostream&
ostream&
ostream&
istream&

dec(ios&);
hex(ios&);
oct(ios&);
endl(ostream& i);
ends(ostream& i);
flush(ostream&);
ws(istream&);





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
format flags, to avoid polluting the global name space. The io_states are described inthis section under "Error states". The format fields are also described in this sectionunder "Formatting". The open_modes are described in detail in fstream under open().
The seek_dirs are described in sbufpub under seekoff().

In the following descriptions, assume:

  • s and s2 are ios
  • sr is an ios&.

  • mode is an int representing an open_mode.

Constructors and assignment

ios(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)
s2=s

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()
init(streambuf * sb)

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 states

An 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.
Normally this indicates that some extraction or conversion has failed, but the stream is still usable. That is, once the failbit is cleared, I/O on s can usually continue.

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.

Operators

Two 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:

if (cin) ...

if (cin >> x) ...

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:

if (!cout) ...

Formatting

An 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.
When skipws is not set, whitespace is not skipped before the extractor begins conversion. In this case zero width fields should not be used, as a precaution againstlooping. So if the next character is whitespace and the skipws variable is not set, thearithmetic extractors signal an error.
If skipws is not set and numeric input is attempted, and the first character of the input is white space, the extraction will fail.
In case of string input the extraction will stop at the first white space character. In thespecial case that the first character in the input stream is white space, nothing will be extracted.
In both cases the input stream will be read until the first white space character is found and then no further.

left
right
internal

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
collectively identified by the static member, ios::adjustfield. The fill character is controlled by the fill() function, and the width of padding is controlled by the
width() function.

dec
oct
hex

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
fixed

These flags control the format to which a floating point value is converted for insertion into a stream.

  • If scientific is set, the value is converted using scientific notation, where there is one digit before the decimal point and the number of digits after it is equal to the precision (see below), which is six by default.
  • If uppercase is set, an uppercase E introduces the exponent; a lowercase appears otherwise.
  • If fixed is set, the value is converted to decimal notation with precision digits after the decimal point, or six by default.
  • If neither scientific nor fixed is set, then the value is converted using either notation, depending on the value: scientific notation is used if the exponent
    resulting from the conversion is less than -4 or greater than or equal to the precision. Otherwise, decimal notation is used.
  • If showpoint is not set, trailing zeros are removed from the result and a decimal point appears only if it is followed by a digit.

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
system call for each character output. Unit buffering makes a C runtime system call for each insertion operation, and doesn’t require the user to call ostream::flush().
In BS2000, a call to ostream::flush() terminates the record and starts a new record.

stdio

When set, stdout and stderr are flushed by ostream::osfx() after each insertion.
In BS2000 this means that the current line (record) is terminated and subsequent data is written to a new line (record).

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 to be hex, you could write:

s.setf(ios::hex, ios::basefield)

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:

  • Output: When the field width is zero (the default), inserters only insert as many characters as necessary to represent the value being inserted. When the field width is non-zero, the inserters insert at least that many characters.

    If the value being inserted requires fewer than field-width characters to be represented, the fill character is used to pad the value. However, the numeric inserters never truncate values, so if the value being inserted does not fit in fieldwidth characters, more than field-width characters are output.

    The field width is always interpreted as a minimum number of characters; there is no direct way to specify a maximum number of characters.

    The field width format variable is reset to the default (zero) after each insertion.

  • Input: A setting of the field width applies only for the extraction of char* and unsigned char*, see istream. When the field width is non-zero, it is taken to be the size of the array, and no more than width-1 characters are extracted.

    The field width format variable is reset to the default (zero) after each extraction.

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 flags

Several 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 members

streambuf* 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.
Since, in BS2000, output to stdout (SYSOUT) implies a subsequent change of line, behaviour for C++ input/output is not as expected for synchronization with C input/output: Each C++ output is written to a separate line. If synchronization is not used, the order of output is undefined.

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
automatic "flushing" of ioss. If the tie variable is nonnull and an ios needs more
characters or has characters to be consumed, the ios pointed at by the tie variable isflushed. By default, cin is tied initially to cout so that attempts to get more charactersfrom standard input result in flushing standard output. Additionally, cerr and clog aretied to cout by default. For other ioss, the tie variable is set to zero by default.

ostream * osp=s.tie()
Returns the "tie" variable.

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 manipulators

Some convenient manipulators (functions that take an ios&, an istream&, or an ostream& and return their argument, (see manip)) are:

sr<<dec
sr>>dec

These set the conversion base format flag to 10.

sr<<hex
sr>>hex

These set the conversion base format flag to 16.

sr<<oct
sr>>oct

These set the conversion base format flag to 8.

sr>>ws
Extracts whitespace characters. See istream.

sr<<endl
Ends a line by inserting a newline character and flushing. See ostream.
Under BS2000, writing a newline character to a text file implies a change of record.

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.
(The standard streams cin, cout, cerr, and clog are members of "withassign" classes, so they can be assigned to, as in cin=inputfstream.)

SEE ALSO


iosintro, istreammanip, ostreamsbufprot, sbufpub