www.digitalmars.com Home | Search | CTG | RTL | IDDE | STL | C/C++ Compiler | D
Last update Thu Apr 13 20:39:46 2006
Runtime Library
Reference


· Constants
· Data types

Standard C
· assert.h
· complex.h
· ctype.h
· fenv.h
· float.h
· locale.h
· math.h
· setjmp.h
· signal.h
· stdarg.h
· stddef.h
· stdio.h
· stdlib.h
· string.h
· time.h


Standard C++
· IOstream
· new


Win32
· gc.h


DOS, DOS32, Win16
· bios.h
· cerror.h
· disp.h
· dos.h
· dos.h part 2
· emm.h
· handle.h
· int.h
· msmouse.h
· sound.h
· swap.h
· tsr.h
· winio.h


Other C
· bitops.h
· conio.h
· controlc.h
· direct.h
· fltpnt.h
· io.h
· page.h
· process.h
· search.h
· sys\stat.h
· tabsize.h
· trace.h
· utime.h
· unmangle.h
· util.h


Other C++
· regexp.h
· class complex


IOstream

This chapter consists of: This chapter does not have descriptions of the classes and functions. Chapter 27, "Iostream Library Class Descriptions," has descriptions of the classes and functions.

C++, like C, has no built-in input or output statements. Instead, I/O facilities are provided by a library. The standard C++ I/O library is the iostream library.

As with much of object oriented programming, iostreams can be difficult to understand without reading through the material more than once. A terminology section defines many of the basic terms.

Predefined Iostreams

The four predefined iostreams are:

  • cin, connected to standard input.
  • cout, connected to standard output.
  • cerr, connected to standard error.
  • clog, connected to standard error.
The predefined iostreams are fully buffered, except for cerr. See the "Output Using Iostreams" and "Input Using Iostreams" sections.

Basic Structure of Iostream Interaction

The iostream library allows a program to use any number of input or output streams. Each stream has some source or sink, which might be one of the following:

  • Standard input
  • Standard output
  • A file
  • An array of characters
A stream can be restricted to input or output, or a single stream can allow both input and output. The iostream library implements these streams using two processing layers.

  • The lower layer implements sequences, which are simply streams of characters. These sequences are implemented by the streambuf class, or by classes derived from it.

  • The upper layer performs formatting operations on sequences. These formatting operations are implemented by the istream and ostream classes, which have as a member a pointer to an object of a type derived from class streambuf. An additional class, iostream, is for performing input and output on streams.
Standard input and output are handled by special class objects derived from class istream or ostream.

The ifstream, ofstream, and fstream classes, which are derived from istream, ostream, and iostream respectively, handle input and output with files.

The istrstream, ostrstream, and strstream classes, which are derived from istream, ostream, and iostream respectively, handle input and output to and from arrays of characters.

When you want to open an input or output stream, you create an object of one of these types. You associate the streambuf member of the stream with a device or file. You generally do this association through the stream constructor, so you don't deal with the streambuf directly. The iostream library predefines stream objects for the standard input, standard output, and error output, so you don't have to create your own objects for those streams.

You use operators or iostream member functions to insert data into a stream (output) or extract data from a stream (input), and to control the format of data that you insert or extract.

To insert and extract a new data type (that is, one of your classes), you generally overload the insertion and extraction operators.

Iostream Terminology

The iostream libarary descriptions use the following terms, which are similar to terms from general programming but with specialized meanings.

Term/Definition
buffer
A word with two meanings, one specific to the iostream package and one more generally applied to input and output.

When referring specifically to the iostream library, a buffer is an object of the type defined by the class streambuf.

A buffer, generally, is a block of memory used to make efficient transfer of characters for input or output. With buffered I/O, the actual transfer of characters is delayed until the buffer is full or forceably flushed.

This confusion allows such odd phrases as "an unbuffered buffer", which refers to a streambuf where there is no buffer in the first sense defined above. Because of this confusion, this chapter avoids use of the term buffer to refer to streambufs. However, the next chapter and other C++ documents use the term buffer to mean streambufs.

extraction
The process of taking input from an iostream.

fstream
An input or output stream for use with files.

insertion
The process of sending output into an iostream.

iostream
Generally, an input or output stream but can also refer to any of the classes in the iostream library.

Iostream library
The library implemented by header files iostream.h, fstream.h, strstream.h, iomanip.h, and stdiostream.h. Because iostream is an object-oriented library, you should extend it. So, some of what you can do with the iostream library is not implemented.

stream
An iostream, fstream, strstream, or user-defined stream.

streambuf
A buffer that contains a sequence of characters with a put or get pointer, or both. It refers generally to any object of class streambuf or a class derived from streambuf. Any stream object contains an object, or a pointer to an object, of a type derived from streambuf.

strstream
An iostream for use with character arrays.

Using Iostreams

To use iostream routines, include the header files for the part of the library you need. The header files are:

Header File/Description
iostream.h
Declares basic features of iostream library.
fstream.h
Declares iostreams and streambufs specialized to files. Includes iostream.h.
strstream.h
Declares iostreams and streambufs specialized to character arrays. Includes iostream.h.
iomanip.h
Declares manipulators (values you insert into or extract from iostreams to have different effects).
fstream.h (obsolete)
Declares iostreams and streambufs specialized to use stdio FILEs. Includes iostream.h. stream.h (obsolete) For compatibility with old-style streams from C++ version 1. 2. Includes iostream.h, fstream.h, iomanip.h, and stdiostream.h

Output Using Iostreams

Output using iostreams usually relies on the overloaded left shift operator (<<) which, in the context of iostream, is called the insertion operator. To send a value to standard output, insert the value in the predefined output stream cout and use the insertion operator. For example:

cout << someValue;

The insertion operator, overloaded for all built-in types, converts the value of someValue to its correct output representation. If, for example, someValue is a float value, the << operator converts the value to the correct sequence of digits and includes a decimal point. Where it inserts float values on the output stream, << is called the float inserter. In general, given a type X, << is called the X inserter. The format of output and how to control it is discussed in the "Format Control" section.

The iostream library does not know about user-defined types. If you define types for output, you must define an inserter (that is, overload the << operator) to handle them correctly.

The << operator may be applied repetitively. To insert two values on cout, use the statement:

cout << someValue << anotherValue;

Output shows no space between the two values. To include spaces in the output use the statement:

cout << someValue << " " << anotherValue;

The << operator has the precedence of the left shift operator (its built-in meaning). As with other operators, you can always use parentheses to guarantee the order of action. It is often a good idea to use parentheses to avoid problems of precedence. Of the following four statements, the first two are equivalent, but the last two are not.

cout << a+ b; // + has higher precedence than <<
cout << (a+ b);
cout << (a& y);// << has precedence higher than &
cout << a& y;// probably an error: (cout << a) & y

Defining Your Own Insertion Operator
The string class defined in the "Sample Program" section has this definition:

class string {
private: 
   char* data;
   size_t size; 

public: 
   (functions not relevant here) 

friend ostream& operator<<(ostream&, 
       const string&); 
friend istream& operator>>(istream&, string&); 
}; 
The insertion and extraction operators in this case must be defined as friends because the data part of the string class is private. The definition of operator<< overloaded for use with strings is:

ostream& operator<< (ostream& ostr, 
         const string& output) 
{ return ostr << output. data;}
operator<< takes a reference to an ostream& as its first argument and returns the same ostream, making it possible to combine insertions in one statement:

cout << string1 << string2;

Handling Output Errors
Checking for errors when overloading operator<< is not necessary because the iostream library can propagate errors.

When an error occurs, the iostream where it occurred enters an error state. Bits in the iostream's state are set according to the general category of the error. The inserters defined in iostream ignore attempts to insert data into any stream that is in an error state, so such attempts do not change the iostream's state.

In general, the recommended way to handle errors is to check the state of the output stream periodically in some central place. If an error exists, you should handle it in some way. This chapter assumes that you define a function error, which takes a string and aborts the program. error is not a predefined function. See "Handling Input Errors" for an example of an error function. Examine the state of an iostream with the operator !, which will return a nonzero value if the iostream is in an error state. For example:

	if (! cout) error("output error"); 
Another way to test for errors exists. The ios class defines operator void *() so it returns a NULL pointer when an error occurs. This allows you to use a statement like this:

if (cout << x) return ; // return if successful 
You can also use the function good, a member of ios:

if (cout. good() ) return; // return if successful 
The error bits are declared the definition of class ios in the enum:
enum io_state {goodbit= 0, eofbit= 1, failbit= 2, 
                badbit= 4, hardfail= 0x80} ; 
Flushing
As with most I/O libraries, iostream often accumulates output and sends it on in larger and generally more efficient chunks. To flush the buffer, simply insert the special value flush. For example:

cout << "Needs to get out immediately." << flush; 
flush is a kind of object known as a manipulator, which is a value that may be inserted into an iostream to have some effect other than causing output of its value. It is really a function that takes an ostream& or istream& argument and returns its argument after performing some actions on it (see "Manipulators").

Binary Output
To obtain output in the raw binary form of a value, use the member function write as:

cout. write((char*)& x, sizeof(x)); 
This, however, violates type discipline by converting &x to char*. Doing so is normally harmless, but if the type of x is a class with pointers, virtual member functions, or one that requires nontrivial constructor actions, the value written by the above example cannot be read back in properly.

Input Using Iostreams

Input using iostream is similar to output. Use the extraction operator >> and string together extractions the way you can with insertions. For example to get two values from standard input:

cin >> a >> b ; 
As with other overloaded operators, the extractors used depend on the types of a and b (and two different extractors are used if a and b have different types). The format of input and how you can control it is discussed in some detail in "Format Control". In general, though, leading whitespace characters (spaces, newlines, tabs, form-feeds, and so on) are ignored.

Defining Your Own Extraction Operators

When you want input for a new type, you overload the extraction operator for it, just as you overload the insertion operator for output.

Class string (shown in sections "Output Using Iostreams" and "Sample Program") defines its extraction operator like this:

istream& operator>> (istream& istr, string& input) 
{ 
   const int maxline = 256; 
   char holder[maxline]; 
   istr. get(holder, maxline, '\n'); 
   input = holder; 
   return istr; 
} 
By convention, an extractor converts characters from its first argument (in this case, istream& istr), stores them in its second argument (always a reference) and returns its first argument. The second argument must be a reference because an extractor is meant to store the input value in its second argument.

The char* Extractor

This predefined extractor is mentioned here because it can cause problems. You use it like this:

char x[50];
cin >> x; 
The extractor skips leading whitespace and extracts characters and copies them to x until it reaches another whitespace character. It then completes the string with a terminating null (0) character. Be careful because input can overflow the given array.

Reading Any Single Character

The char extractor skips whitespace, which can be a problem if your program needs to read the next character whether or not it is whitespace. To do this with either form of function get member:

char c;
cin. get(c); // leaves c unchanged if input fails

int b;
b = cin. get(); // sets b to EOF if input fails
To skip only blanks, stopping on a tab, newline, or any other character:

int a;
do { 
    a = cin. get(); 
while(a == ' ' ); 
Binary Input

To read binary values (such as those written with the member function write), use the read member function. To input the raw binary form of x using the read member function, do the following, which is the inverse of the earlier example that used write.

cin. read((char*)& x, sizeof(x)); 
Peeking at Input

Use the peek member function to look at the next character in the stream without extracting it. For example:

if (cin. peek() != c) return 0; 
Extracting Whitespace

By default, iostream extractors skip leading whitespace. You can turn off the skip flag to prevent this from happening. The following code turns off whitespace skipping from cin, then turns it on again.

cin. unsetf(ios::skipws); // turn off . . . 

cin. setf(ios::skipws, ios::skipws); // turn on
You can use the iostream manipulator ws to remove leading whitespace from the iostream, whether or not skipping is enabled. To remove the leading whitespace from iostream istr:
istr >> ws; 

Handling Input Errors

By convention, an extractor whose first argument has a nonzero error state should not extract anything from the input stream and should not clear any error bits. An extractor that fails should set at least one error bit.

As with output errors, you should check the error state periodically and take some action (such as aborting) when you find a nonzero state. The ! operator returns the error state of an iostream. For example, the following code produces an input error if you type alphabetic characters for input:

#include <stream.h> 
#include <stdlib.h>
void error (const char* message) { 
   cout << message << "\n" ; 
   exit(1); 
} 
main() { 
   cout << "Enter some characters: "; 
   int bad; 
   cin >> bad; 
   if (! cin) error(" aborted due to input error"); 
   cout << "If you see this, not an error." << 
"\n"; 
   return 0; 
} 
Class ios has member functions that you can use for error handling. See the next chapter.

Using Iostreams with stdio

You can use stdio with C++ programs, but problems can occur when you mix iostreams and stdio in the same standard stream within a program. For example, if you write to both stdout and cout, independent buffering will occur; results might not be what you expect. The problem is worse if you input from both stdin and cin, since independent buffering can turn the input into trash.

To eliminate this problem with standard input, standard output, and standard error, use the following instruction before performing any input or output. It connects all the predefined iostreams with the corresponding predefined stdio FILEs.

ios::sync_with_stdio(); 
Such a connection is not the default because a significant performance penalty occurs when the predefined streams are made unbuffered as part of the connection. You can use both stdio and iostreams in the same program applied to different files with no difficulty. That is, you can write to stdout using stdio routines and write to other files attached to iostreams. You can open stdio FILEs for input and also read from cin so long as you do not also try to read from stdin.

Creating Iostreams

To read or write a stream other than the predefined iostreams, you must create your own iostream. In general that means creating objects of types defined in the iostream library. The following sections discuss the various types available.

Dealing with Files Using Class fstream

Dealing with files is similar to dealing with standard input and standard output; classes ifstream, ofstream, and fstream are derived from classes istream, ostream and iostream, respectively. As derived classes, they inherit the insertion and extraction operations (along with the other member functions) and also have members and constructors for use with files.

You must include the file fstream.h to use any of the fstreams. Use an ifstream when you only want to perform input, an ofstream for output only, and an fstream for a stream on which you want to perform both input and output. Use the name of the file as the constructor argument.

For example, to copy the file thisFile to the file thatFile:

ifstream fromFile(" thisFile");
if (! fromFile) 
   error(" unable to open 'thisFile' for input"); 
ofstream toFile (" thatFile"); 
if (!toFile ) 
   error(" unable to open 'thatFile' for output"); 
char c ; 
while (toFile && fromFile. get(c)) toFile. put(c); 
This code:
  • Creates an ifstream object called fromFile with a default mode of ios: in and connects it to thisFile (it opens thisFile).
  • Checks the error state of the new ifstream object and, if it is not 0, calls the error function (which must be defined elsewhere in the program).
  • Creates an ofstream object called toFile with a default mode of ios::out and connects it to thatFile.
  • Checks the error state of toFile.
  • Creates a char variable to hold the data while it is passed.
  • Copies the contents of fromFile to toFile one character at a time.
Note
You would not really copy a file this way, one character at a time. This code is provided only as an example of using fstreams. Instead, insert the streambuf associated with the input stream into the output stream.

Open Mode
The mode is constructed by or-ing bits from the enumerated type open_mode, which is an public type of class ios and has the definition:

	enum open_mode {in= 1, out= 2, ate= 4, app= 8, 
		trunc= 0x10, nocreate= 0x20, noreplace= 0x40}; 
You can open a file for both input and output. For example, the following code opens file someName for both input and output, attaching it to the fstream variable inoutFile.

fstream inoutFile("someName", ios::in | ios::out); 
Declaring an fstream Without Specifying a File
You can declare an fstream without specifying a file and open the file later. For example, to create the ofstream toFile for writing.
ofstream toFile; 
toFile.open(argv[1], ios::out); 
Opening and Closing Files
You can close the fstream and then open it with another file. For example, to process a list of files provided on the command line:

	ifstream infile; 
	for (char** f = &argv[1]; *f; ++f)
	{   
	   infile.open(*f, ios::in);
	   ...; 
	   infile.close();
	} 
Opening a File Using a File Descriptor
If you know a file descriptor (such as the integer 1 for standard output), you can open it like this:

ofstream outfile; 
outfile. attach(1); 
When you open a file by providing its name to one of the fstream constructors or by using the open function, the file automatically closes when the fstream is destroyed (by a delete or when it goes out of scope). When you attach a file to an fstream, it does not automatically close.

Repositioning Within a File
Several tools can alter the reading and writing position in a file.

  • streampos, a type that records a position in an iostream.

  • tellg (tellp), an istream (ostream) member function that reports the file position. Since istream and ostream are the parent classes of fstream, tellg and tellp can also be invoked as a member function of the fstream class.

  • seekg (seekp), an istream (ostream) member function that finds a given position.

  • seek_dir, enum that specifies relative positions for use with seek:

    enum seek_dir {beg= 0, cur= 1, end= 2 }

For example, given an fstream aFile:

	streampos original = aFile.tellp(); // save current position
	aFile.seekp(0, ios::end); 	    // reposition to end of file
	aFile << x; 			    // write a value to file
	aFile.seekp(original); 		    // return to original position
seekg (seekp) can take one or two parameters. When it has two parameters, the first is a position relative to the position indicated by the seek_dir value given as the second parameter. For example, to move 10 bytes from the end:

	aFile.seekp(-10, ios::end); 
To move 10 bytes forward from the current position:

	aFile.seekp(10, ios::cur); 
Note
Arbitrary seeking on text streams is not portable.

Assigning Iostreams

Earlier versions of C++ allowed assignment of one stream to another. This is no longer allowed.

The problem with copying a stream object is that when two versions of the state information exist (such as a pointer to the current write point within an output file) each might be changed independently. This can cause problems. Copying stream objects is usually not necessary.

Format Control

Format control is described in the next chapter.

Manipulators

A manipulator is a value you can insert into or extract from iostreams to have special effects.

Because manipulators are ordinary identifiers, and therefore use up possible names, iostream does not define them for every possible function. Manipulators are listed and described in the next chapter.

To use predefined manipulators, include header file iomanip.h in your program.

You can define your own manipulators. The two basic kinds of manipulators are:

  • Plain manipulator
  • Parameterized manipulator.
Plain Manipulators

A plain manipulator is a function that

  1. Takes a reference to a stream (takes an istream&, ostream&, or ios& argument).
  2. Operates on it in some way.
  3. Returns its argument.
The shift operators taking (a pointer to) such a function are predefined for iostreams, so the function may be put in a sequence of input or output operators. The shift operator calls the function rather than trying to read or write a value.

An example of a tab manipulator that inserts a tab in an ostream:

 ostream& tab(ostream& os) { 
         return os << '\t' ; 
	 } 
 ... 
 cout << x << tab << y ; 
This is an elaborate way to achieve what could be done with:

 const char tab = '\t'; 
 ... 
 cout << x << tab << y; 
Here is another example, which cannot be accomplished with a simple constant. Suppose you want to turn whitespace skipping on and off for an input stream. You can use separate calls to ios::setf and ios::unsetf to turn the skipws flag on and off, or you could define two manipulators:

ostream& skipon(istream &is) { 
       is. setf(ios::skipws, ios::skipws); 
       return is; 
} 

ostream& skipoff(istream& is) { 
       is. unsetf(ios::skipws); 
       return is; 
} 

 ... 
cin >> skipon >> x >> skipoff >> y; 
Parameterized Manipulators

A parameterized manipulator takes one or more parameters. It:

  1. Takes an istream&, ostream&, or ios& argument, one additional argument (the parameter).
  2. Operates on the stream.
  3. Returns its stream argument.
One of the parameterized manipulators in iomanip.h is setfill. setfill sets the character that fills out field widths. It is implemented as:

	// file setfill.cpp 
	#include <iostream.h>
	#include <iomanip.h>

	// the private manipulator 
	static ios& sfill(ios& i, int f) { 
		 i.fill((char) f); 
		 return i; 
	} 

	// the public applicator 
	smanip_int setfill(int f) { 
		return smanip_int(sfill, f); 
	} 
A parameterized manipulator is implemeted in two parts:

  • manipulator
  • applicator
The manipulator looks like any other manipulator, except it takes an extra parameter. In the previous code example, it takes an extra int parameter. You cannot place this manipulator function in a sequence of input or output operations, since no shift operator is defined for it. Instead, you must use an auxiliary function- the applicator.

The applicator calls the manipulator. The applicator is a global function, and you make a prototype for it available in a header file. Usually the manipulator is a static function in the file containing the source code for the applicator. The manipulator is called only by the applicator. If you make it static, its name stays out of the global address space.

Several classes are defined in the header file iomanip.h. Each class holds the address of a manipulator function and the value of one parameter. Chapter 27, "Iostream Library Class Descriptions," describes iomanip classes. The previous example uses the smanip_int class, which works with an ios. Because it works with an ios, it also works with an istream and an ostream. The previous example also uses a second parameter of type int.

The applicator creates and returns a class object. In the previous code example the class object is an smanip_int, and it contains the manipulator and the int argument to the applicator. The iomanip.h file defines the shift operators for this class. When the applicator function setfill appears in a sequence of input or output operations, the applicator function is called, and it returns a class. The shift operator acts on the class to call the manipulator function with its parameter value, which was stored in the class.

In the next code example, the manipulator print_hex does the following:

1. Puts the output stream into the hex mode.

2. Inserts a long value into the stream.

3. Restores the conversion mode of the stream.

The class omanip_long is used because this code example is for output only, and it operates on a long rather than an int.

	static ostream& xfield(ostream& os, long v)
	{ 
		long save = os. setf(ios::hex, ios::basefield); 
		os << v; 
		is. setf(save, ios::basefield); 
		return s; 
	}
 
	omanip_long print_hex(long v)
	{ 
		return omanip_long(xfield, v); 
	} 

strstreams: Iostreams for Arrays

See strstream in the next chapter.

stdiobufs: Iostreams for stdio FILEs

See stdiobuf in the next chapter.

Streambufs

Iostreams are the formatting part of a two-part (input or output) system. The other part of the system is made up of streambufs, which deal in input or output of unformatted streams of characters.

You usually use streambufs through iostreams, so you don't have to worry about the details of streambufs. You can use streambufs directly if you choose to, for example, if you need to improve efficiency or to get around the error handling or formatting built in to iostreams.

How Streambufs Work

A streambuf consists of a stream or sequence of characters and one or two pointers into that sequence. Each pointer points between two characters. (Pointers cannot actually point between characters, but it is helpful to think of them that way.)

° One is a put pointer, which points just before the position of the next character delivered.

° The other is a get pointer, which points just before the next character that will be fetched.

A streambuf can have one or both of these pointers.

Position of Pointers
The positions of the pointers and the contents of the sequences can be manipulated in various ways. Whether or not both pointers move when manipulated depends on the kind of streambuf used. Generally, with queue-like streambufs, the get and put pointers move independently; with file-like streambufs the get and put pointers always move together. A strstream is an example of a queue-like stream; an fstream is an example of a file-like stream.

Using Streambufs

You never create an actual streambuf object, but only objects of classes derived from class streambuf. Examples are filebuf and strstreambuf, which are described in filebuf and ssbuf, in the next chapter. You can derive your own classes from streambuf, to provide an interface to a special device, or to provide other than basic buffering. sbuf. pub and sbuf. prot, in the next chapter, discuss how to do this.

Apart from creating your own special kind of streambuf, you might want to access the streambuf associated with an iostream to get at the public member functions. In addition, each iostream has a defined inserter and extractor that take a streambuf pointer. When a streambuf is inserted or extracted, the entire stream is copied.

Here is another way to copy a file, with the error checking omitted.

 
ifstream fromFile("thisFile");
ofstream toFile ("thatFile"); 
toFile << (streambuf*) fromFile. rdbuf(); 
Open the input and output files as before. Every iostream class has a member function rdbuf which returns a pointer to the streambuf object associated with it. In the case of an fstream, the streambuf object is type filebuf. Cast the filebuf* to a streambuf* so the appropriate inserter is called, and the entire file associated with fromFile is copied (inserted into) the file associated with toFile. The last line can also be written like this:

fromFile >> (streambuf*) toFile. rdbuf(); 
In this case, the source file is extracted into the destination. The two methods are equivalent.

Sample Program

Here is a sample C++ program. It has a '' toy'' implementation of a string class, and a small program to test it. The class is a '' toy'' because it is not full-featured, yet it shows a number of features a real class must have.

Header file

The header file str.h for the string class string is:

/****************** str.h **********************/ 
/* header file str.h for toy C++ strings package 
*/ 
#include <string.h> /* for C string functions */ 
class ostream; /* to declare output of strings 

class string { 
public: 
   string(); 
   string(char *); 
   void append(char *); 
   const char* str() const; 
   string operator+ (const string&) const; 
   const string& operator=(const string&); 
   const string& operator=(const char*); 

private: 
   char *data; 
   size_t size; 
}; 
inline string::string() {size = 0; data = NULL;} 
inline const char* string::str() const { 
   return data;} 
ostream& operator<<(ostream&, const string&); 
istream& operator>>(istream&, string&); 

Implementation file

The implementation file str.cpp of the string class functions is:

/******************* str.cpp *********************/ 
/* implementation for toy C++ string package */ 

#include <iostream.h>
#include "str.h" 

string::string(char *aStr) 
{ 
   if (aStr == NULL) 
      size = 0; 
   else 
      size = strlen(aStr); 

   if (size == 0) 
      data = NULL; 
   else { 
      data = new char [size+ 1]; 
      strcpy(data, aStr); 
   } 
}
void string::append(char *app) 
{ 
   size_t appsize = app ? strlen(app) :0; 
   char *holder = new char [size + appsize + 1]; 

   if (size) 
      strcpy(holder, data); 
   else 
      holder[0] = 0; 

   if (app) { 
      strcpy(& holder[size], app); 
      size += appsize; 
   } 
   delete [] data; 
   data = holder; 
} 
string string::operator+(
      const string& second) const 
{ 
      string temp; 
      temp. data = new char[size + second. size + 1] 

      if (size) 
         strcpy(temp. data, data); 
      else 
         temp. data[0] = 0; 

      if (second. size) 
	strcpy(& temp. data[size], second. data); 
	temp. size = size + second. size; 
	return temp; 
} 
const string& string::operator=(
	const string& second) 
{ 
   if (this == &second) 
      return *this; /* in case string = string */ 

   delete [] data; 
   if (second. size) { 
      data = new char[second. size+ 1]; 
      size = second. size; 
      strcpy(data, second. data); 
   } 
   else { 
      data = NULL; 
      size = 0; 
   } 
   return *this; 
} 
const string& string::operator=(const char* str) 
{ 
   delete [] data; 

   if (str && str[0]) { 
      size = strlen(str); 
      data = new char[size+ 1]; 
      strcpy(data, str); 
   } 
   else { 
      data = NULL; 
      size = 0; 
   } 
   return *this; 
} 
ostream& operator<< (
      ostream& ostr, const string& output) 
{ 
   return ostr << output. data; 
} 
istream& operator>> (
      istream& istr, string& input) 
{ 
   const int maxline = 256; 
   char holder[maxline]; 
   istr. get(holder, maxline, '\n'); 
   input = holder; return istr; 
} 

Test file

The test file testr.cpp to test the string class is:

/******************* testr.cpp********************/ 
/* test code for toy C++ strings package */ 

#include <iostream.h> 
#include "str.h" 

main() 
{ 
   string first ("This is a string."); 
   cout << "first: " << first <<"\n"; 

   string sec; 
   sec = first; 
   cout << "sec = first: " << sec << "\n"; 

   sec = "And this is another."; 
   cout << "another sec: " << sec << "\n"; 

   cout <<" Type in a string ....."; 
   cin >> sec; 
   cout << "sec: "<< sec << "\n" 

   string third; 
   third = sec+ first; 
   cout << "sec + first: " << third << "\n"; 

   third = sec+ sec; 
   cout << "sec + sec: " << third << "\n"; 

   third. append("plus"); 
   cout << "with append:" << third << "\n"; 

   third = third + sec; 
   cout << "added to itself:" << third << "\n"; 

   return 0; 
} 

Compile and link the program

To compile and link the entire program use the command:

sc -cpp -o testr testr.cpp str.cpp 

Runtime Library Reference 27 Iostream Library Class Descriptions


T his chapter contains descriptions for:

° Iostream classes

° Iostream functions

For an overview of Iostreams, see Chapter 26.

Note
This version of Digital Mars C++ implements a different iostream class library than previous versions of Digital Mars C++ or Zortech C++. If your code uses iostream classes from previous releases, you must convert to the classes described here; the old classes are not supported.

Manipulators

A manipulator provides a convenient way to work with extractors and inserters. It embeds what is really a function call into a sequence of insertions or extractions. A manipulator appears to be an object inserted or extracted into a stream, but usually it only changes the state of the stream.

For example, instead of writing:

cout. width(8);
cout << val1 << " ";
cout. width(4);
cout << val2 << '\n';
cout. flush();

you can write:

cout << setw(8) << val1 << " " << setw(4) \
   << val2 << endl; 
Classes ios, istream, and ostream all implement predefined manipulators. These are simple, taking no arguments such as endl, above, does. A manipulator can also take arguments, such as setw does. Header file defines some of these manipulators and provides the definitions for creating your own manipulators.

Manipulators are logically defined as templates but were introduced before templates were available in the C++ language. They are accordingly defined as macros simulating templates. The macro IOMANIPdeclare(typ) expands to a complete set of definitions for a manipulator taking one parameter of type typ. Due to the nature of the macros, the type parameter must be a simple type name (just an identifier). The header provides the expanded definitions for types int and long.

Simple Manipulators

A manipulator without arguments is a function with one parameter of type reference to stream, and which returns the same type. The streams have predefined overloaded operators that take such a function as a parameter. The manipulator performs whatever operations are necessary on the stream argument, then returns the same stream. For example, this code implements a tab manipulator:

ostream& tab(ostream& s) 
{ 
   s << '\t'; 
   return s; 
} 
In the expression cout<< tab, the overloaded operator ostream& operator<< (ostream& (*)(ostream&)) is selected; it calls the manipulator function. The resulting call inserts a tab character into the ostream.

Parameterized Manipulators
A manipulator with a parameter has two parts:

°A manip part, a function taking a stream and a typ argument and returning the stream;

°An apply part, the function invoked by the manip part, which applies state changes or other operations.

For a given type typ, all arts are declared by the IOMANIPdeclare macro. These are described below.

The following declarations are used in the discussion below:

Variable/Declaration

typ
Some type name
n
An int
l
A long
s
An ios
i
An istream
o
An ostream
io
An iostream
f
An ios& (*) (ios&)
if
An istream& (*) (istream&)
of
An ostream& (*) (ostream&)
iof
An iostream& (*) (iostream&)
s << SMANIP(typ)(f, t)
s << SAPP(typ)(f)(t)
s >> SMANIP(typ)(f, t)
s >> SAPP(typ)(f)(t)
Returns f(s, t). The stream s can also be
any of the other stream types i, o, or
io.
i >> IMANIP(typ)(if, t)
i >> IAPP(typ)(if)(t)
Returns if(i, t).
o << OMANIP(typ)(of, t)
o << OAPP(typ)(of)(t)
Returns of(o, t).
io << IOMANIP(typ)(iof, t)
io << IOAPP(typ)(iof)(t)
io >> IOMANIP(typ)(iof, t)
io >> IOAPP(typ)(iof)(t)
Returns iof(io, t).

The header contains declarations for manipulators taking an int or a long argument (typ in the above presentation). Predefined manipulators are used for changing the state of a stream:

Manipulator/Description

o << setw(n)
i >> setw(n)
Sets the field width of stream i or o to n. The next formatted insertion or extraction resets the width to 0.
o << setfill(n)
i >> setfill(n)
Sets the fill character of stream i or o to n.
o << setprecision(n)
i >> setprecision(n)
Sets the precision variable of stream i or o to n. o << setiosflags(l)
i >> setiosflags(l)
Turns on the ios flags of stream i or o that are set in l.
o << resetiosflags(l)
i >> resetiosflags(l)
Turns off the ios flags of stream i or o that are set in l.

To write a parameterized manipulator:

1. Declare function manip, and then implement functions manip and apply.
2. If the manipulator will take an argument of type typ, declare function manip to take one argument of that type, and to return an object of type Xmanip_typ.
3. Replace X with either s, i, o, or io, if the intention is to manipulate objects of type ios, istream, ostream, or iostream, respectively.
4. Replace typ with the actual type name. For types int and long, all declarations are in place. For other types, invoke the "template" IOMANIPdeclare(typ).

Function apply is usually static, called by only the manip function. Define it to return a reference to the type of stream to be manipulated, to have a first parameter of that same type, and a second of type typ.

For example, consider the setiosflags manipulator. The manipulator operates on an ios, and takes a long parameter, so it is declared to return type smanip_long. If it operated on an ostream and took an int parameter, it would be declared to return type omanip_int. The manipulator (the manip function) is therefore declared in the header like this:

	smanip_long setiosflags(long); 
The apply function does not appear in the header; it is never called directly by user code. Code for both functions appears in the implementation module:

// set the flags bitvector according to the bits
// set in b static ios& sios(ios& i, long b) 
// private apply function 
{
   i. setf(b); 
   return i; 
} 
smanip_long setiosflags(long b) 
// public manip function { 
   return smanip_long(sios, b); 
} 

Class filebuf

The filebuf class is a specialization of streambufs using a file as the source or destination of characters. Characters are fetched (input) from a file and consumed by (written to) a file.

A filebuf object has a file attached to it. When filebuf is connected (attached) to an open file, filebuf is said to be open; otherwise it is closed. A file is opened by default with protection mode filebuf::openprot, which is 0644.

If seek operations can be performed on the attached file, class filebuf supports seeks. For example, an ordinary disk file is seekable, the terminal is not. If the attached file allows reading and/ or writing, the filebuf allows fetching and/ or storing. For example, standard input allows only reading, standard output allows only writing. Unlike C stdio calls, no seek is required between gets and puts to the same filebuf. At least four characters of putback are initially allowed.

Class streambuf provides basic streambuf operations. The reserve area is allocated automatically if one is not supplied to a constructor or with a call to filebuf::setbuf (calls to setbuf are usually honored). If the filebuf is unbuffered, each input and output character requires a system call. Pointers get and put act like a single pointer; conceptually, they are tied together.

A filebuf operates on files by way of a Unix-style file descriptor, a small integer passed in system calls. C stdio calls are not used.

Note
Supplied file descriptors are not checked for validity. The filebuf does not report seek failures.

Member Functions of filebuf

Class filebuf is derived from streambuf, so you can use all the streambuf member functions on objects of class filebuf.

The following functions are members of class filebuf.

filebuf constructors

Header

fstream.h

Prototype

filebuf();
filebuf(int f);
filebuf(int f, char *ptr, int len);

Description

The default constructor filebuf() creates a closed filebuf.

filebuf(f) creates an open filebuf attached to file descriptor f, which is assumed to be open.

filebuf (f, ptr, len) creates an open filebuf attached to file descriptor f, which is assumed to be open. This constructor uses the array of len chars beginning at ptr as the initial reserve area. If ptr is zero or len is not greater than zero, the filebuf is unbuffered.


filebuf::attach

Header

fstream.h

Prototype

filebuf * filebuf::attach(int f);

Description

If filebuf is closed, this function connects it to file descriptor f, which is assumed to be open, and returns the address of filebuf. If filebuf is already open, it ignores f and returns zero.


filebuf::close

Header

fstream.h

Prototype

filebuf * filebuf::close();

Description

This function flushes any pending output, unconditionally closes the file descriptor, and closes filebuf. It returns the address of filebuf, or zero if an error occurs.


filebuf::fd

Header

fstream.h

Prototype

int filebuf::fd();

Description

This function returns the file descriptor attached to filebuf, or EOF if filebuf is not open.


filebuf::is_open

Header

fstream.h

Prototype

int filebuf::is_open();

Description

This function returns non-zero if filebuf is open (connected to a file descriptor), and zero otherwise.


filebuf::open

Header

fstream.h

Prototype

filebuf * filebuf::open(const char *name, int mode, int prot= filebuf::openprot);

Description

If filebuf is not already open, this function opens file name and connects its file descriptor to filebuf; otherwise an error occurs. This function returns the address of filebuf on success, or zero on any failure.

If the file does not exist, and ios::nocreate is not set in mode, open attempts to create the file with the protection bits specified in prot (with default value 0644). Parameter mode is a collection of bits from ios::open_mode, described in fstream::open, which can be or'd together.


filebuf::seekoff

Header

fstream.h

Prototype

streampos filebuf::seekoff(streamoff off, ios::seek_dir dir, int mode);

Description

This function moves the combined get/ put pointer, described in "Class streambuf (Public Interface)", except parameter mode is ignored. It returns the new file position on success, or EOF if a failure occurs.

If filebuf is not open, if the attached file does not support seeking, or if the seek cannot otherwise be performed (such as off either end of the file), the operation fails. The position of the file in the event of an error is undefined.


filebuf::seekpos

Header

fstream.h

Prototype

streampos filebuf::seekpos(streampos pos, int mode=(ios::in | ios::out));

Description

This function is equivalent to the call filebuf. seekoff((streamoff) pos, ios::beg, mode). The value of pos is obtained from a previous call to seekoff or seekpos, or the value zero representing the beginning of the file. It returns the new file position on success, or EOF if a failure occurs.


filebuf::setbuf

Header

fstream.h

Prototype

streambuf * filebuf::setbuf(char *ptr, int len);

Description

If filebuf is open and a reserve area has been allocated, no change is made and setbuf returns zero. Otherwise, the new reserve area becomes the len chars beginning at the location pointed to by ptr, and the function returns the address of filebuf. The function returns the address of the filebuf object, or zero if filebuf is already open and has a reserve area allocated for it.

If ptr is zero or len is not greater than zero, there will be no reserve area and filebuf is unbuffered.


filebuf::sync

Header

fstream.h

Prototype

int filebuf::sync();

Description

This function attempts to synchronize the get/ put pointer with the actual position of the attached file. This might involve flushing unwritten characters or backing up the file over characters already input. It returns zero if successful, otherwise EOF.

To ensure that a group of characters is written to a file at the same time, allocate a reserve area larger than the largest such group, call sync() just before storing the characters, and then call sync() again just after.



Classes fstream, ifstream, and ofstream

Classes fstream, ifstream, and ofstream do the following:

  • fstream implements input and output streams for files
  • ifstream implements input streams for files
  • ofstream implements output streams for files
Each class uses a filebuf object as a buffer to coordinate operations between the stream and the file.

Auxiliary class fstreambase is an implementation detail, primarily providing a set of common functions. It is not documented.

Member Functions of fstream, ifstream ofstream

Class fstream is derived from iostream, which in turn is derived from ios. You can use ios and iostreams member functions on fstream objects.

Class ifstream is derived from istream, which in turn is derived from ios. You can use ios and istreams member functions on ifstream objects.

The following functions are members of fstream, ifstream, and ofstream class. The notation Xstream is used to collectively describe the member functions.

Xstream constructors

Header

fstream.h

Prototype

Xstream(); 
Xstream(int f); 
Xstream(const char *name, int mode= ios::in, 
   int prot= filebuf::openprot); 
Xstream(int f, char *ptr, int len); 
Description

The default constructor Xstream() constructs a closed xstream, not connected to any file.

Xstream(f) constructs an Xstream attached to file descriptor f, which must already be open; It does not test for this condition. The file will not be closed automatically when the stream is destroyed.

Xstream(name, mode, prot) constructs an Xstream and opens file name using mode for the Xstream::open mode bits and prot for the file protection bits. The default open mode is input for an ifstream and output for an ofstream. The default protection is filebuf::openprot, which is 0644. Errors will be stored in the Xstream error state; see "Error States" in the description of class ios. The file closes automatically when the stream is destroyed.

Xstream(f, ptr, len) constructs an Xstream attached to file descriptor f, which must already be open; it does not test for this condition. The filebuf uses len chars beginning at the location pointed to by ptr as the buffer (reserve area). If ptr is zero or len is not greater than zero, there will be no reserve area and filebuf will be unbuffered. The file will not be closed automatically when the stream is destroyed.


Xstream::attach

Header

fstream.h

Prototype

Xstream::attach(int f);

Description

This function connects Xstream to an open file descriptor f. If Xstream is already connected to a file, it ignores the request, and sets ios::failbit in the Xstream error state. The attached file will not be closed automatically when the stream is destroyed.


Xstream::close

Header

fstream.h

Prototype

Xstream::close();

Description

This function closes the associated filebuf and disconnects the file from Xstream. If the filebuf's close call succeeds, it clears the error state; otherwise it sets ios::failbit in the Xstream error state.


Xstream::open

Header

fstream.h

Prototype

Xstream::open(const car *name, int mode= ios::in, int prot= filebuf::openprot);

Description

This function opens file name and connects its file descriptor to Xstream. If the file does not exist, and ios::nocreate is not set in mode, open attempts to create the file with the protection bits specified in prot (with default value 0644). Parameter mode is a collection of bits from ios::open_mode that can be or'd together. The opened file closes automatically when the stream is destroyed. The following creation modes are supported:

Mode/Description
ios::app
Initially seeks to the end of the file. Any subsequent write operation always appends to the end of the file. This flag implies ios::out.
ios::ate
Initially seeks to the end of the file. This flag does not imply ios::out, but only begins operations at end of file.
ios::in
Opens the file for input. Construction or opening of an ifstream always implies this bit; the bit need not be set. When set for an fstream, it means that input is allowed if possible. When set for an ofstream, it means that the file is not truncated when it is opened.
ios::nocreate
If the file does not already exist, do not create it; open will fail in this case. This bit makes sense only when opening for output.
ios::noreplace
The file must not already exist; otherwise open fails. This bit makes sense only when opening for output.
ios::out
Open the file for output. Construction or opening of an ofstream always implies this bit, meaning the bit need not be set. When set for an fstream, it means that output is allowed if possible. This bit can be set for an ifstream, but output to the file is not permitted.
ios::trunc
If the file exists, truncate to zero length upon opening it. When ios::out is specified or implied and neither ios::ate nor ios::app is specified, this bit is implied. This bit makes sense only when opening for output.


Xstream::rdbuf

Header

fstream.h

Prototype

filebuf * Xstream::rdbuf();

Description

This function returns a pointer to the filebuf associated with Xstream. It works like its counterparts in the base classes, except that its return type is specifically a filebuf.


Xstream::setbuf

Header

fstream.h

Prototype

Xstream::setbuf(char *ptr, int len);

Description

This function sets up a buffer of len chars at ptr as the reserve area. It calls filebuf::setbuf, and uses its return value to adjust the error state of Xstream. That is, it clears the error state on success, and sets ios::failbit on error.



Class ifstream

Class ifstream, a specialization of class istream, implements input streams for files. It uses a filebuf object as a buffer to coordinate operations between the stream and the file.

The section "Classes fstream, ifstream, and ofstream" discusses fstream, ifstream, and ofstream together, using the notation Xstream.


Class ios

Class ios is a virtual base class of all stream objects. It describes common aspects of input and output streams, such as tracking errors, controlling representation and interpretation of numbers, and monitoring buffers. ios also provides the basic state and formatting data for a stream.

Class ios defines several enumerations and collection of functions. Although you never create an object of class ios, you can use many of its member functions to check the state of a stream and to control formatting.

Class ios Enumerations

Class ios defines the enumerations described below.

io_state

Member functions use these enumerations to keep track of the error state of the stream. See "Error States" for information on how to test these bits. io_state is really a collection of bits, as follows

badbit
This bit indicates that some operation on the associated streambuf has failed. Typically, further operations will not succeed, even after clearing the bit. Example situations would be an output error, or immediate end of file on an attempted input operation.
eofbit
This bit is normally set when end of file has been reached during an extraction. It is not set as the result of a succesful extraction reaching end of file, but when end of file is reached while attempting further extractions. '' End of file'' in this sense is an abstraction as defined by the streambuf associated with the stream. Normally this bit is not set for output streams.
failbit
This bit is set when an attempted extraction or conversion has failed, usually due to unexpected characters. Further attempted extractions will fail until this bit is cleared, to prevent running on after improper input. Usually the stream is still usable, and extraction can be continued after clearing the bit and dealing with the unexpected input.
goodbit
This '' bit'' is really the absence of any error bits, and indicates that the stream is in a good state.
hardfail
This bit is reserved by the implementation to indicate that the stream cannot be further used. Typically it represents a hardware failure of some kind. The bit cannot be cleared by any publicly accessible function.

open_mode
These enumerations are described with function fstream::open.

seek_dir
These enumerations are described in the section "Class streambuf (Public Interface)", under the function streambuf::seekoff.

Formatting Flags
Member functions use these enumerations of anonymous type to control input and output formatting. See "Format Control".

Constructors and Assignment

Class ios defines the following constructors, which are described in the "Member Functions of ios" section.

ios(sbptr) 
ios() 		// protected 
init(sbptr) 	// protected 
ios(iosref) 	// private 

Error States
Functions that enable testing and adjusting the error state bits, are:

Function/Description

bad()
Checks whether the stream can be used.
clear(flags)
Clears the error state.
eof()
Checks whether the eofbit is set.
fail()
Checks whether the operation failed.
good()
Checks whether any error state bits are set.
rdstate()
Returns the error state bits of a stream.

Other Status Testing It is often convenient to be able to test the state of a stream directly. Since typical insertion and extraction operators return a reference to the stream, you can test the return values of the operations. Two operators are defined to permit this testing: void* and !.

The operator void* ()
You can use an explict cast of a stream to void*, or use a stream in a boolean context to test its state. The result is 0 if any of failbit, badbit, or hardfail is set. The result is a non-zero pointer if the stream is in a good or eof state. For example:

if(cout ) ... // next output should succeed
if(cin >> x ) ... // input to x succeeded 
The operator ! ()
This operator provides the inverse of the above testing. The result is non-zero if any of failbit, badbit, or hardfail is set, and zero otherwise. For example:

if(! cout ) ... // output will not succeed
if(! (cin >> x) ) ... // input to x failed 

Format Control

A ios object maintains a format state that is controlled by formatting flags, in combination with the three functions fill, width, and precision. The formatting flags are a collection of bits described below, declared as enumerations of an anonymous type. These format bits are kept in a long int and can be manipulated independently via two versions of the flags function.

Formatting flags can be set and cleared independent of other operations. They change only by explicit programmer action.

Formatting Flags
ios defines the following format flags:

Flag/Description

skipws
If this flag is set, formatted extractors will skip leading whitespace; otherwise, leading whitespace is not skipped. This flag is set by default, allowing free-format input text. Unformatted extractors do not examine this flag.
left
right
internal
These flags control how padding is inserted during formatted operations. At most one of these three flags can be set at one time. The three flags can be addressed as a unit by the static member ios::adjustfield. If left is set, the value is left-adjusted in its field width, meaning that padding is added on the right. If right is set, the value is right-adjusted in its field width, meaning that padding is added on the left. If internal is set, padding is added after any leading base or sign field, and before the value. The default (none of the flags set) is right. The fill character used for padding defaults to the space character, and can be set with the fill function. The amount of padding is determined by the field width as set by the width function. See the section "Manipulators" for more information.
dec
oct
hex
These flags control the conversion base of integer data. At most one of these three flags can be set at one time. The three flags can be addressed as a unit by the static member ios::basefield. Conversions are done in decimal (base 10) if dec is set, in octal (base 8) if oct is set, or in hexadecimal (base 16) if hex is set. If no flag is set, insertions are done in decimal, and extractions are converted according to the C++ rules for representing integer constants. That is, a leading '' 0x'' or '' 0X'' results in hex conversion, a leading '0' results in octal conversion, and a leading '1' through '9' results in decimal conversion for extraction. The default is none of these bits set. Manipulators dec, oct, and hex can also be used to set the conversion base as described in the section "ios Predefined Manipulators".
showbase
If this flag is set, insertions of converted integral values will be in the form used for representing C++ integer constants. That is, octal values will begin with a leading '0', and hexadecimal values will begin with a leading '' 0x'' or '' 0X'' (see '' uppercase'' below). The default is unset.
showpos
If this flag is set, a plus sign ('+ ') will be added to insertions of converted positive decimal values (including floating point numbers). The default is unset.
uppercase
If this flag is set, an uppercase 'X' will be used in insertions of converted hexadecimal values when showbase is set, and an uppercase 'E' will be used for floating point conversions. Otherwise, lowercase 'x' and 'e' will be used, respectively. The default is unset.
fixed
scientific
These flags control the type of conversion used when floating point values are converted for insertion. The two flags can be addressed as a unit by the static member ios::floatfield. The rules for conversion are generally the same as for the C stdio function printf. If scientific is set, 'e' format is used. If fixed is set, 'f' format is used. If neither is set, 'g' format is used (see also uppercase above). The value set by width, if any, is used as the printf field width specification. The value set by precision, if any, is used as the printf precision specification.
showpoint
If this flag is set, trailing zeros, or a trailing decimal point, will appear in the conversion of floating point values. The default is to truncate trailing zeros or a trailing decimal point.
unitbuf
If an output stream is buffered, the buffer is flushed when it fills, or when it is explicitly flushed. This can result in delayed output, or lost output if the program crashes. A stream can be unbuffered, eliminating delays and lost output, but at the cost of a system call per character output. If the unitbuf flag is set, the buffer will be flushed after each complete insertion. Unit buffering is thus a compromise, providing frequent output at lower cost than unbuffered output, and not requiring extra flush() calls in the program source. In particular, unit buffering can be turned on and off at selected places in the code without changing any other source code. By default, this flag is not set.
stdio
This flag causes the C stdio files stdout and stderr to be flushed after each insertion in the stream. This can be useful when C stdio operations on the standard files is mixed with iostreams on other files. By default, this flag is not set.

Format Bit Masks
ios predefinesdefines the following bit mask as type long with the following OR'd definitions. Use them to set and clear specific groups of bits, helping to avoid conflicting specifications:

Bit mask/Definition
adjustfield
left| right| internal
basefield
dec| oct| hex
floatfield
fixed| scientific

Format Control Functions
ios defines the following member functions for format control:

Function/Description
fill(char)
Gets or sets the fill character
flags(long)
Gets formatting flags
precision(int)
Gets or sets the precision setting
setf(long, long)
Sets formatting flags
unsetf(long)
Clears any flag bits that are set
width(int)
Gets or sets the field width

User-defined Format Flags and Variables

User-defined format flags and variables are provided for derived classes that might need their own. Once allocated for a class, the flags and variables are reserved for the duration of the program; several independent classes can allocate their own flags and variables without conflict. The following functions return values you can use as flags:

Function/Description
bitalloc
Allocates a flag bit
iword
ipword
Gets a reference to a user-defined status variable.
xalloc
Returns an index to be used with iword or ipword.

ios Predefined Manipulators

A manipulator can appear to be an inserted or extracted object, but really only changes the state of the stream. The following manipulators are predefined for use with streams. Additional manipulators are available when you include manip.h file. See the section "Manipulators" for more information.

Manipulator/Description
s >> dec
s << dec
Set the conversion base of stream s to 10.
s >> oct
s << oct
Set the conversion base of stream s to 8.
s >> hex
s << hex
Set the conversion base of stream s to 16.
s >> ws
Extracts and discards whitespace from stream s. See the overloaded operator >> in class istream.
s << endl
Inserts a newline into stream s and flushes the stream. See overloaded operator << in class ostream.
s << ends
Inserts a null character ('\0') into stream s to end the string. See class strstream.
s << flush
Flushes the stream s. See class ostream.

Member Functions of ios
Class ios is a virtual base class for ostream, istream, and iostream, so you can use any ios member functions on objects of any of these types, and on types derived from them.

The following functions are members of class ios.

ios constructors

Header

iostream.h

Prototype

ios(streambuf* sbptr);

ios(); 					// protected 
void init(streambuf* sbptr); 		// protected 

ios(iosref); 				// private 
void operator=(ios&); 			// private; 

Description

Historically, a virtual base class requires a default constructor (one with no arguments), because arguments could not be passed to a constructor for a virtual base class. Class ios therefore has a default constructor ios() and a separate intialization function init(sbptr) whose argument is a pointer to a streambuf.

A derived class uses protected constructor ios() by default, and calls initialization function init(sbptr). The argument to init(sbptr) points to the streambuf to be associated with the ios object being constructed, and must not be null. For example:

class istream : virtual public ios { ... }; 
istream::istream(streambuf* s) 
{ 
   ios::init(s); 
   // ... 
} 
For the constructor of the form ios(sbptr), the streambuf pointed to by sbptr becomes the streambuf associated with the ios being constructed. The pointer must not be null.

The copy constructor ios(iosref) and assignment operator stream2= stream1 are private to prevent copying of ios objects, since the effect of such copying is not well defined. Usually, you want to copy a pointer to the object, or pass a reference to a function.


ios:bad

Header

iostream.h

Prototype

int ios::bad();

Description

Checks if badbit or hardfail is set. Returns non-zero if either is set, otherwise returns zero.


ios:bitalloc

Header

iostream.h

Prototype

long ios::bitalloc();

Description

This static member function returns a long with one previously unallocated flag bit set. This value can then be used as a flag for class-specific purposes (in calls to setf, for example). At least 16 bits are available for allocation. When no bits are available, this function returns zero.


ios:clear

Header

iostream.h

Prototype

ios::clear(int flags= 0);

Description

This function stores its int parameter as the error state of the stream. The value of flags is derived only from the return of rdstate and/ or combinations of the io_state bits. To clear only one bit in the stream state, use something like:

ios::clear(~ ios::failbit & ios::rdstate());


ios:eof

Header

iostream.h

Prototype

int ios::eof();

Description

This function returns non-zero if the eofbit is set, and zero otherwise.


ios:fail

Header

iostream.h

Prototype

int ios::fail();

Description

This function returns non-zero if any of failbit, badbit, or hardfail is set, and zero otherwise.


ios:fill

Header

iostream.h

Prototype

char ios::fill();
char ios::fill(char newfill);

Description

fill() returns the current fill character of the stream. The fill character pads an insertion to the designated field width. See the discussion of the flags left, right, and internal in "Format Control".

fill(newfill) returns the old fill character. The default fill character is the space. See the description of the predefined manipulator setfill in the section "Manipulators".


ios:flags

Header

iostream.h

Prototype

long ios::flags();
long ios::flags(long newflags);

Description

flags() returns the current formatting flags of the stream in a long.

flags(newflags) uses the long value of newflags to replace all the formatting flags in the stream. It returns the previous formatting flags in a long.


ios::good

Header

iostream.h

Prototype

int ios::good();

Description

This function returns non-zero if the error state is good; that is, if no bits are set. Otherwise, it returns zero. In particular, it returns zero if eofbit is set.


ios:iword, ios:pword

Header

iostream.h

Prototype

long ios::iword(int i);
void * ios::pword(int i);

Description

When i is an index value returned by a call to ios::xalloc, these functions return a reference to the ith user-defined status variable (word) for class ios. Function iword returns the reference typed as a long; function ipword returns the reference typed as a void*.

Note
Do not depend on the returned reference being stable for an indefinite period. In particular, any call to ios::xalloc() can invalidate a previous reference.


ios::precision

Header

iostream.h

Prototype

int ios::precision();
int ios::precision(int newprec);

Description

precision() returns the current '' precision'' format state of stream ios. It controls the number of significant digits converted in floating point insertions. See the section "Format Control" .

precision(newprec) sets the '' precision'' format state of stream s to newprec, and returns the old value. The default value is 6. See the description of the predefined manipulator setprecision in the section "Manipulators" for more information.


ios::rdbuf

Header

iostream.h

Prototype

streambuf *ios::rdbuf();

Description

This function returns a pointer to the streambuf associated with the stream. This is part of the construction of a stream, and the buffer class object is not normally changed. This function can be used to get at streambuf functions directly, given a stream object.


ios:rdstate

Header

iostream.h

Prototype

int ios::rdstate();

Description

This function returns the error state bits of stream ios as an int.


ios:setf

Header

iostream.h

Prototype

long ios::setf(long newflags);
long ios::setf(long newflags, long field);

Description

For setf(newflags), each bit that is set in the long value newflags is set in the formatting flags of stream ios. The remaining formatting flags are unaffected. It returns the previous formatting flags in a long. Note that the ios::flags function replaces all the flag bits, while the ios::setf function sets just those bits that are specified.

setf(newflags) is most useful for setting a flag that is not part of a group. setf(newflags, field) is useful for setting one of a group of flags.

For setf(newflags, field), bits that are set in the long value field mark the formatting flags that are replaced by the corresponding bits in the long value newflags. It returns the previous value of the designated flags. Typically, the field value is one of the bit masks basefield, adjustfield, or floatfield (see "Format Bit Masks").

Example

This example sets left-justification, outputs a value, and restores the previous justification:

	long oldadjust = cout. setf(ios::left, \
	   ios::adjustfield); 
	cout << data; 
	cout. setf(oldadjust, ios::adjustfield); 
This technique ensures that only one of the adjustfield bits is ever set, and allows convenient restoration of the previous status. Using zero for the new value of the field will clear just those flags.

This code clears the integer conversion base to the default state:

	cout. setf(0, ios::basefield);

See the descriptions of the predefined manipulators setiosflags and resetiosflags in the "Manipulators" section.


ios::sync_with_stdio

Header

iostream.h

Prototype

ios::sync_with_stdio();

Description

If C stdio and C++ stream operations are performed on the same standard file, synchronization problems will occur. Since each style of I/O has its own buffering, I/O will not occur in the order of program execution.

To solve this synchronization problem, call this static function before doing I/O to standard streams cin, cout, cerr, or clog; the function resets the standard streams to use class stdiobuf. I/O via stdio and streams will then be synchronized. A substantial performance degradation occurs, however, compared to using buffered stream I/O or buffered stdio.

Note
Call sync_with_stdio only when doing I/O to the same standard input, output, or error file. Using exclusively stdio input functions on stdin and exclusively stream output functions on cout does not cause problems.


ios::tie

Header

iostream.h

Prototype

ostream * ios::tie(ostream *osp); ostream * ios::tie();

Description

A stream can be '' tied'' to one ostream, kept track of by the tie stream variable. Whenever a stream needs to acquire more input or flush its output, the tied stream, if any, is flushed first. For example, cin is initially tied to cout, so that pending output, such as a prompt, will be flushed before new input is attempted.

tie(osp) sets the tie variable of stream s to the ostream pointed to by input parameter osp, and returns the old value of the tie variable. This code unties a stream while some work is done, and then restores the previous tie:

ostream* oldosp = s. tie(0);
... do something ...
s. tie(oldosp);

tie returns the current value of the tie variable.


ios:unsetf

Header

iostream.h

Prototype

long ios::unsetf(long newflags);

Description

Each bit set in the long value newflags is unset in the formatting flags of stream ios. The remaining formatting flags are unaffected. The function returns a long containing the previous formatting flags.

Function setf sets corresponding flag bits, while function unsetf clears them. See the description of predefined manipulator resetiosflags in "Manipulators" for more information.


ios:width

Header

iostream.h

Prototype

long ios::width();
long ios::width(int newwidth);

Description

width() returns the current field width format state of stream ios. If the field width is zero, inserters will insert only the characters necessary to represent the value being inserted. If the field width is greater than the number of characters needed, the field will be padded with the fill character to the specified width. If the field width is less than the number of characters needed, the width will be extended. Field width represents the minimum field width; it cannot be used to provide truncation to a maximum field width.

width(newwidth) sets the field width format state of stream s to newwidth, and returns the old value. The default value is 0. The field width is reset to zero automatically after every formatted insertion or extraction. It must therefore be reset for each operation requiring a field width. See the description of the predefined manipulator setw in "Manipulators" for more information.


ios::xalloc

Header

iostream.h

Prototype

int ios::xalloc();

Description

This static member function returns a previously unused index into an array of words. A word is big enough to contain a long or a void*. This index can then be used with functions iword or ipword to get a reference to a reserved status variable.



Class istream

Class istream defines the behavior of input streams. It supports formatted and unformatted extraction (input) of data from an associated streambuf.

istream works in combination with class ostream, which defines the behavior of output streams.

Formatted Input (extraction) Functions

These functions work with formatted input. They call the setup function ipfx(0). If it returns zero, no further action takes place. Otherwise, leading whitespace is stripped if ios::skipws is set. If only whitespace remains in the istream, no characters will remain and the ios::failbit will be set.

istream defines the following formatted input function.

istr >> sbufp
This function extracts characters from istr and inserts them into the streambuf pointed to by sbufp. It always returns a reference to istream. You can use this function to copy a stream efficiently, but be sure neither stream is tied. For example:

	#include <iostream.h>
	main() 
	{ // copy cin to cout 
	  cin. tie(0); 
	  cout. tie(0); 
	cin >> cout. rdbuf(); // see ios for 
	                      // rdbuf return 0; 
	}
istr >> x
This function extracts characters from istream and converts them according to the type of x. If ipfx returns zero, no characters are extracted and x is unchanged. Errors encountered are recorded in the error state of istream. In general, ios::failbit means the next available characters were not suitable for the type; for example, leading letters for a numeric type, or leading whitespace for any type. Offending characters are not extracted. Generally, ios::badbit means no characters could be extracted, as in attempting to extract past the end of file. These functions always return a reference to istream. User-written functions must conform to these principles and be of the form:

istream& operator>> (istream&, SomeType)

The type of x and the format state of the istream (described in class ios) determine details of the extraction and conversion. These functions do not change the state of the istream, although the width variable is reset to zero after each formatted extraction. The predefined formatted extractors are:

Extractor/Description
char&
unsigned char&
Extracts one character and stores it in x.

short&
unsigned short&
int&
unsigned int&
long&
unsigned long&
Extracts characters and converts them to an integral value according to the conversion base in the istream's format flags, and stores the value in x. The first character can be a plus ('+ ') or minus ('-') sign. The characters are then treated as decimal, octal, or hexadecimal, if the ios::basfield flags are dec, oct, or hex, respectively. If none of these flags is set, the number is interpreted in the same way as integer constants in C++. That is, if the first two characters are "0x" or "0X" the base is hex; otherwise, if the first character is '0' the base is octal; otherwise the base is decimal.

Extraction (and thus conversion) stops with the first non-digit, which is not extracted. Valid digits are '0'-' 7' for octal, '0'-' 9' for decimal, and '0'-' 9', 'a'-' f', 'A'-' F' for hexadecimal. Error flag ios::failbit is set if no valid digits are encountered. A "0x" followed by a non-digit is an error. In case of an error, the value of x is not changed.

float&
double&
Extracts characters and converts them to a floating point value according to the C++ rules for floating point constants, and stores the value in x. The error flag ios::failbit is set if the characters extracted do not begin a well-formed floating point number; some characters can be extracted in this case, depending on at what point the error is detected. In the case of an error, the value of x is not changed.

char*
unsigned char*
Extracts characters and stores them in the array pointed to by x until a whitespace character is encountered. The whitespace is not extracted (but ipfx might have discarded leading whitespace). If the width formatting variable (see the description of class ios) is non-zero, at most width-1 characters are extracted. A terminating null (0) is always stored in x, even when nothing is extracted. The error flag ios::failbit is set if no characters are available for extraction.

Unformatted Input (extraction) Functions

These functions perform conversions on unformatted input. They call the setup function ipfx(1). If a function returns zero, no further action takes place. Leading whitespace is not skipped, and no conversions take place. See descriptions of the functions in "Member Functions of istreams". Unformatted input functions are:

Function/Description
get
Gets the next character(s) from the stream.
getline
Gets lines from the stream.
ignore
Gets characters and discards them.
read
Gets characters until EOF is encountered.

Positioning Functions

These functions position the get pointer of the streambuf associated with an istream. See the section "Class streambuf (Public Interface)"

Function/Description
istream::seekg(pos)
Sets the position of the get pointer; returns istream.
istream::seekg(offset, dir)
Sets the position of the get pointer; returns istream.
streampos istream::tellg()
Returns the current position of the get pointer.

istream Predefined Manipulators

A manipulator can look like an inserted or extracted object, but often only changes the state of the stream. See "Manipulators" and "ios Predefined Manipulators" for more information.

These manipulators are predefined for use with istreams:

Manipulator/Description
istr >> manip
Equivalent to the call manip(istr).
istr >> dec
Sets the conversion base of istr to 10.
istr >> oct
Sets the conversion base of istr to 8.
istr >> hex
Sets the conversion base of istr to 16.
istr >> ws
Extracts and discards consecutive whitespace characters from istr.

Member Functions of istreams

Class istream is derived from class ios, so you can use all of the ios member functions on an istream object.

The following functions are members of class istreams.

istream constructors

Header

iostream.h

Prototype

istream(streambuf *sbufp);

Description

istream(sbufp) associates the streambuf pointed to by sbufp with the stream and initializes the ios state.


istream::gcount

Header

iostream.h

Prototype

istream::gcount

Description

This function returns the number of characters extracted from istr by the last unformatted input function.

Note that formatted input functions might call unformatted input functions, thus changing the count.


istream::get

Header

iostream.h

Prototype

int istream::get();
istream::get(char& c);
istream::get(char *ptr, int count, char delim= '\n');
istream::get(streambuf & sbuf, char delim= '\n');

Description

get() extracts the next character from istream and returns it. It returns EOF if no more characters are available; however, it never sets ios::failbit.

get(c) extracts the next character from istr and stores it in c. It stores EOF if no more characters are available; it sets ios::failbit when attempting to extract beyond EOF. This function always returns a reference to istream.

get(ptr, count, delim) extracts characters from istr and stores them in the char array beginning at ptr. Extraction stops after count-1 characters have been extracted or when a character matching delim is encountered, whichever happens first. If a delim character is encountered, it is not extracted or stored. This function always stores a terminating null (0) even if nothing is extracted. It sets ios::failbit only if EOF is encountered before any characters are stored. This function always returns a reference to istream.

istream::get(sbuf, delim) extracts characters from istr and stores them in the streambuf sbuf. Extraction stops when a character matching delim (or EOF) is encountered, or when a store into sbuf fails, whichever happens first. If a delim character is encountered, it is not extracted or stored. If delim is EOF, extraction stops only when input is exhausted or when a store operation fails. This function sets ios::failbit only if a store into sbuf fails;. it always returns a reference to istream.


istream::getline

Header

iostream.h

Prototype

istream::getline(char *ptr, int count, char delim= '\n');

Description

This function is the same as istream::get(ptr, count, delim), except delim, if encountered, is extracted but not stored. Once count-1 characters have been extracted, the next character is left in istream, even if it is delim. This function always returns a reference to istream.


istream::ignore

Header

iostream.h

Prototype

istream::ignore(int count= 1, int delim= EOF);

Description

Extracts characters from istr and discards them. Extraction stops when a character matching delim is encountered, when count characters have been extracted, or when EOF is encountered, whichever happens first; the delim character is extracted. If delim is EOF, all input is discarded. This function always returns a reference to istream.


istream::ipfx

Header

iostream.h

Prototype

int istream::ipfx(int noform= 0);

Description

This function performs setup procedures common to all extraction operations. Formatted extractors call ipfx(0); unformatted extractors call ipfx(1).

If the error state of istream is non-zero, ipfx returns zero immediately. If a stream is tied to istream (see ios::tie) and noform is zero, the tied stream is flushed. If flag skipws is set for the stream and noform is zero, leading whitespace characters (defined by iswhite, see ctype(3V)), are skipped. This function returns zero if an error condition is encountered; non-zero otherwise.


istream::peek

Header

iostream.h

Prototype

int istream::peek();

Description

This function first calls istream::ipfx(1). If ipfx returns zero or if istr is at EOF, it returns EOF. Otherwise, it returns the next character without extracting it.


istream::putback

Header

iostream.h

Prototype

istream::putback(char c);

Description

If istream::fail() returns non-zero, this function returns without doing anything. Otherwise, it attempts to back up the streambuf associated with istr by pushing back character c.

Because it does not extract, putback does not call ipfx. It may fail, setting ios::failbit. In general, c must match the character ahead of the streambuf's get pointer (normally the last character extracted) -input might come from a read-only in-memory buffer.


istream::read

Header

iostream.h

Prototype

istream::read(char *ptr, int count);

Description

This function extracts characters from istr and stores them in the char array beginning at ptr. Extraction stops after count characters are extracted or when EOF is encountered, whichever happens first. This function always returns a reference to istream.

read sets ios::failbit if EOF is encountered before count characters are extracted. The number of characters extracted can be found by calling istream::gcount().


istream::sync

Header

iostream.h

Prototype

int istream::sync();

Description

This function forces a correspondence between internal data structures and the external source of characters in an implementation-defined manner. It calls the virtual function istream::rdbuf()-> sync(); the result depends on the actual type of the buffer class. This function returns EOF if an error occurs.



Class istream_withassign

Class istream_withassign implements the assignment operator for istream objects. Use it to redirect stream input to other streams.

Member Functions of istream_withassign

Class istream_withassign is derived from class istream. You can use all istream and ios member functions on istream_withassign objects. The following functions are members of class istream_withassign.

istream_withassign constructor

Header

iostream.h

Prototype

istream_withassign();

Description

istream_withassign() creates an istream_withassign object that can be assigned to, but performs no initialization.


istream_withassign::operator=

Header

iostream.h

Prototype

istream_withassign::operator= (streambuf * sbufp);

istream_withassign::operator= (istream & istr);

Description

The first function associates the streambuf pointed to by sbufp with the istream_withassign object and completely initializes it. The second function associates the streambuf, associated with istr, with the istream_withassign object, which the constructor completely initializes. These functions return a reference to the object it was assigned to.



Class istrstream

Class istrstream supports stream input using in-memory character arrays. An istrstream uses a strstreambuf as a buffer to hold characters in memory. istrstream performs stream input operations on strings or on text stored in memory.

Member Functions of istrstream

Because class istrstream is derived from class istream, which is in turn derived from ios, you can use all of the member functions of ios and istream on an istrstream object. The following functions are members of class istrstream.

istrstream constructors

Header

iostream.h

Prototype

istrstream(char *ptr); istrstream(char *ptr, int len);

Description

istrstream(ptr) assumes ptr points to a null-terminated array of characters, which serves as the input source. Null is not part of the input. Seeks, using istream::seekg, are permitted within the range of the array. istrstream(ptr, len) assumes ptr points to an array of characters of length len, which will serve as the input source. Seeks, using seekg, are permitted within the range of the array.


istrstream::rdbuf

Header

iostream.h

Prototype

strstreambuf * istrstream::rdbuf();

Description

This function returns a pointer to the strstreambuf associated with istrstream. It works like its counterparts in the base classes, except that its return type is specifically a strstreambuf*.



Class ofstream

Class ofstream, a specialization of class ostream, implements output streams for files. It uses a filebuf object as a buffer to coordinate operations between the stream and the file.

The section "Classes fstream, ifstream, and ofstream" discusses fstream, ifstream, and ofstream together, using the notation Xstream.


Class ostream

Class ostream defines behavior for output streams. It supports formatted and unformatted insertion (output) of data to an associated streambuf. ostream works in combination with class istream, which defines the behavior of input streams.

Output Prefix and Suffix Functions

These functions perform setup and cleanup actions before and after insertion operations:

Function/Description

opfx
Performs setup for insertion operations
osfx
Performs cleanup after insertion operations

Formatted Output (insertion) Functions

These functions work with formatted output. They call setup function opfx(). If zero returns, no further action takes place. These functions also call osfx() before returning (if opfx succeeded). The following output functions are defined by ostream.

ostr << sbufp If ostr. opfx() returns non-zero, this function inserts all the characters into ostr that can be extracted from the streambuf pointed to by sbufp. No padding is performed. It returns a reference to ostr.

You can use this function to copy a stream efficiently, but be sure neither stream is tied. For example:

	#include <iostream.h> 
	main() 
	{ // copy cin to cout 
	  cin. tie(0); 
          cout. tie(0); 
	cout << cin. rdbuf(); 
	  // see ios::rdbuf 0; 
	} 

istr << x If ostr. opfx(0) returns non-zero, this function inserts characters representing x into ostr. If opfx returns zero, no action is taken. Errors encountered are recorded in the error state of istream. These functions always return a reference to ostr. User-written functions must conform to these principles and be of the form:

ostreama& operator<< (ostream&, SomeType)

The type of x and the format state of the ostream (see the section "Format Control" in the discussion of class ios) determine the details of the conversion and insertion. This kind of function does not change the state of the ostream, except that the width variable is reset to zero after each formatted insertion.

Predefined formatted inserters and their conversion rules are:

Predefined inserters/Conversion rules

char
unsigned char
Inserts the character x into ostr without conversion.
shor
unsigned short
int
unsigned int
long
unsigned long
The representation consists of a sequence of "digits" with no leading zeros. The digits and coversion are octal if ios::oct is set, hexadecimal if ios::hex is set, decimal if ios::dec or none of these is set. For decimal conversion, if x is positive and ios::showpos is set, there is a leading plus sign ('+ '); if x is negative there is a leading minus sign ('-'). The octal and hexadecimal conversions are treated as unsigned; no sign is included.
If ios::showbase is set, there is a leading '0' for octal conversion and a leading "0x" or "0X" ' for hexadecimal conversion, depending on whether ios::uppercase is set.
float double
The value of x is converted according to the current values in ostr of precision, width, ios::scientific, ios::fixed, and ios::uppercase.
char*
The representation is the sequence of characters pointed to by x up to but not including the first null (0) character.

void*
The pointer is converted as if it were an int and ios::showbase and ios::hex were set.

Unformatted Output (insertion) Functions

These functions work with unformatted output. They do not call opfx() or osfx(). See "Member Functions of ostream".

Function/Description

put
Inserts a character into the ostream. Inserts multiple characters into the ostream.

Positioning Functions These functions position the put pointer of the streambuf associated with an ostream. See the "Class streambuf (Public Interface)" section.

Function/Description

ostr.seekp(pos)
ostr.seekp(off, dir)
Sets the position of the put pointer; returns
a reference to ostr.
streampos pos =
ostr.tellp()
Returns the current position of the put
pointer.

ostream Predefined Manipulators

A manipulator can appear to be an inserted or extracted object, but it usually changes only the state of the stream. See the "Manipulators" and "ios Predefined Manipulators" sections. These manipulators are predefined for use with ostreams.

Manipulator/Description

ostr << manip
Equivalent to the call manip(ostr).
ostr << dec
Sets the conversion base of ostr to 10.
ostr << oct
Sets the conversion base of ostr to 8.
ostr << hex
Sets the conversion base of ostr to 16.
ostr << endl
Ends a line by inserting newline and flushing ostr.
ostr << ends
Ends a string by inserting null (0) character into ostr.
ostr << flush
Equivalent to calling ostr. flush().

Member Functions of ostream

Class ostream is derived from class ios; you can use all of the ios member functions on an ostream object. The following functions are members of class ostream.

ostream constructor

Header

iostream.h

Prototype

ostream(streambuf *sbufp);

Description

ostream(sbufp) associates the streambuf pointed to by sbufp with the stream and initializes the ios state.


ostream::flush

Header

iostream.h

Prototype

ostream::flush();

Description

This function causes characters stored in the associated streambuf to be flushed; for example, they are written to the output file. The function returns a reference to ostream.


ostream::opfx

Header

iostream.h

Prototype

int ostream::opfx();

Description

This function performs setup procedures common to all insertion operations. If a stream is tied to ostr (see ios::tie), the tied stream is flushed. If the error state of ostream is non-zero, opfx returns zero immediately. User-defined inserter functions must start by calling opfx.

This function returns zero if an error condition is encountered, non-zero otherwise.


ostream::osfx

Header

iostream.h

Prototype

ostream::osfx();

Description

This function performs cleanup procedures at the conclusion of an insertion operation. If ios::unitbuf is set, flushes the stream. If ios::stdio is set, flushes stdout and stderr. Predefined inserters call osfx, but unformatted output functions do not.

User-defined inserters must call osfx before returning.


ostream::put

Header

iostream.h

Prototype

ostream::put(char c);

Description

This function inserts the character c into ostr. Sets the error state if the operation fails. The function always returns a reference to ostr.


ostream::write

Header

iostream.h

Prototype

ostream::write

Description

This function inserts exactly len characters starting at the beginning of the char array, pointed to by ptr, into ostream. It sets the error state if the operation fails. The function always returns a reference to ostream.



Class ostream_withassign

Class ostream_withassign implements the assignment operator for ostream objects. Use it to redirect stream output to other streams.

Member Functions of ostream_withassign

Because class ostream_withassign is derived from class ostream, you can use all ostream and ios member functions on ostream_withassign objects. The following functions are members of class ostream_withassign.

ostream_withassign constructor

Header

iostream.h

Prototype

ostream_withassign();

Description

ostream_withassign() creates an ostream_withassign object that can be assigned to. However, it performs no initialization.


ostream_withassign::operator=

Header

iostream.h

Prototype

ostream_withassign::operator= (streambuf *sbufp); ostream_withassign::operator= (ostream & ostr);

Description

The first function associates the streambuf pointed to by sbufp with the ostream_withassign object, completely initializing the object. The second function associates the streambuf, associated with ostr, with the ostream_withassign object, which is completely initialized by the constructor. Each function returns a reference to the object it was assigned to.



Class ostrstream

Class ostrstream is a specialization of class ostream. It supports stream output using in-memory character arrays. An ostrstream uses a strstreambuf as a buffer to hold the characters in memory. Use ostrstream to perform stream output operations on strings or on text stored in memory.

Related classes istrstream and strstream are specializations of classes istream and iostream, respectively.

Member Functions of ostrstream Class ostrstream is derived from class ostream, which in turn is derived from ios. You can use all of the member functions of ios and ostream on an ostrstream object.

The following functions are members of class ostrstream.

ostrstream constructors

Header

strstream.h

Prototype

ostrstream();
ostrstream(char *ptr, int len, int mode= ios::out);

Description

ostrstream() creates an empty output stream that uses a dynamic (expandable) array of characters (see class strstreambuf). Seeks are permitted within the current bounds of the array. Presumably this stream will be converted to a char* via str() (see below).

ostrstream(ptr, len, mode) creates an output stream using the static (non-expandable) array of len characters starting at ptr. If the ios::ate or ios::app bits are set in mode, the array is assumed to contain a null-terminated string beginning at ptr. Characters are stored beginning at the null character, but never go beyond len characters. If those bits are not set in mode, the array is assumed to contain no data, and characters will be stored beginning at ptr. Seeks are permitted within the range of the array.


ostrstream::pcount

Header

strstream.h

Prototype

int ostrstream::pcount();

Description

This function returns the number of characters stored in the array. It is useful when the array contains binary data or is not null-terminated.


ostrstream::rdbuf

Header

strstream.h

Prototype

strstreambuf * ostrstream::rdbuf();

Description

This function returns a pointer to the strstreambuf associated with ostrstream. It works like its counterparts in the base classes, except that its return type is specifically a strstreambuf*.



Class stdiobuf

The stdiobuf class is a specialization of streambufs using a C stdio FILE structure as an intermediary to the file that is the source or destination of characters. Input, output, and seek operations are reflected in changes to the associated FILE structure. For example, seek functions are implemented in terms of fseek().

The stdiostream class provides a C++ interface to a C stdio FILE structure. Class streambuf implements basic streambuf operations.

Why Use stdiobuf?

The only reason to use stdiobuf is to integrate existing C stdio code and C++ iostream-like code. If possible, use filebuf for new code; filebuf operations are more efficient because they are buffered.

Member Functions of stdiobuf

Class stdiobuf is derived from streambuf, so you can use all of the streambuf member functions on objects of class stdiobuf.

The following functions are members of class stdiobuf.

stdiobuf constructor

Header

stdiostream.h

Prototype

stdiobuf(FILE *fp);

Description

This function constructs a stdiobuf attached to the FILE structure pointed to by fp.


stdiobuf::stdiofile

Header

stdiostream.h

Prototype

FILE * stdiobuf::stdiofile();

Description

This function returns a pointer to the FILE structure associated with stdioiobuf. The function returns a pointer to FILE structure.



Class stdiostream

The stdiostream class provides a C++ interface to a C stdio FILE structure. It has a stdiobuf as its buffer. It is not a full implementation of iostreams; it has only the buffer-class and ios-class functionality. C++ I/O is done via per-character calls to the C stdio functions getc and putc. Buffering does not occur; it would break synchronization of the C and C++ file accesses.

The stdiobuf class provides a specialization of streambufs using a C stdio FILE structure as an intermediary to the actual file that is the source or destination of characters. Basic streambuf operations are implemented in class streambuf.

Why Use stdiostream?

The only reason to use stdiostream is to integrate existing C stdio code and C++ iostream-like code. If possible, use fstream for new code; fstream operations are more efficient because they are buffered.

Member Functions of stdiostream

Class stdiostream is derived from ios so you can use all of the ios member functions on objects of class stdiostream. The following functions are members of class stdiostream.

stdiostream constructor

Header

stdiostream.h

Prototype

stdiobuf * stdiostream::rdbuf();

Description

Constructs a stdiostream attached to the FILE structure pointed to by fp.


stdiostream::rdbuf

Header

stdiostream.h

Prototype

stdiobuf * stdiostream::rdbuf();

Description

Returns a pointer to the stdiobuf associated with stdiostream. It works like ios::rdbuf() except the return type is a stdiobuf.



Class streambuf (Protected Interface)

The streambuf class is an abstract class for implementing buffers associated with input and output streams. It defines the basics from which actual buffer classes are derived.

The protected interface to streambuf provides functions required to derive a user-defined buffer class. You do not typically create objects of type streambuf; buffer objects are of a class type derived from streambuf. The iostream library provides three predefined derived buffer classes: filebuf, strstreambuf, and stdiobuf.

The public interface to streambuf, described in the section "Class streambuf (Public Interface)", provides functions that any stream class can perform its buffer related operations.

Using the Protected Interface to streambuf

The non-virtual functions in this interface are not intended to be over-ridden; they provide low-level buffer management functions. It is the virtual functions that you will often to override.

Where a virtual function's default behavior is suitable for a derived buffer class, you do not have to override it. For example, a buffer class that has no input source need not do anything on underflow except return EOF, the default behavior. Where the default behavior is not appropriate, you must provide a class-specific version of the function. For example, an input buffer connected to a file attempts to read more data on underflow.

A replacement virtual function conforms to the specification of the streambuf version, to ensure other functions that depend on this behavior will continue to work.

The get, put, and reserve Areas

The buffer of a streambuf has three parts: the get area, the put area, and the reserve area. The get area contains characters immediately available for input. The put area holds characters stored for output but not yet consumed by (flushed to) their ultimate destination. The get and put areas can be disjoint or can overlap. The reserve area is the entire buffer, overlapped by the get and put areas. The get and put areas can expand into the remainder of the reserve area. In the course of input and output operations, the sizes of the get and put areas expand and shrink, always bounded by the total buffer size.

The buffer and its three areas are defined by private pointer variables that you read and set using protected member functions. Think of the following pointers as pointing between characters;