Compaq_C++____________________________________ Class Library Reference Manual Order Number: AA-PY3EB-TK June 1999 This document describes a library of C++ classes. Revision/Update Information: This is a revised manual. Software Version: C++ Version 5.3 or later C++ Class Library Version 4.0 Compaq Computer Corporation Houston, Texas __________________________________________________________ First Printing, September 1992 First Revision, June 1993 Second Revision, April 1996 Third Revision, June 1999 The information in this document is subject to change without notice and should not be construed as a commitment by Digital Equipment Corporation. Digital Equipment Corporation assumes no responsibility for any errors that may appear in this document. The software described in this document is furnished under a license and may be used or copied only in accordance with the terms of such license. No responsibility is assumed for the use or reliability of software on equipment that is not supplied by Digital Equipment Corporation or its affiliated companies. Restricted Rights: Use, duplication, or disclosure by the U.S. Government is subject to restrictions as set forth in subparagraph (c)(1)(ii) of the Rights in Technical Data and Computer Software clause at DFARS 252.227-7013. ©1993-1999 Digital Equipment Corporation. All Rights Reserved. Compaq, the Compaq logo, and Alpha, DEC, DEC FUSE, DECthreads, DIGITAL, OpenVMS, ULTRIX, VAX, VMS are Registered in U.S. Patent and Trademark Office. The following are third-party trademarks: AT&T is a registered trademark of American Telephone & Telegraph Company. UNIX is a registered trademark in the United States and other countries, licensed exclusively through X/Open Company, Ltd. This document is available on CD-ROM. ZK6026 This document was prepared using DECdocument, Version 3.2-1M. ________________________________________________________________ Contents Preface.................................................. vii 1 Overview 1.1 Thread Safe Programming......................... 1-1 2 complex Package Global Declarations............................. 2-2 complex class................................... 2-4 c_exception class............................... 2-11 3 generic Package Global Declarations............................. 3-3 4 iostream Package Global Declarations............................. 4-5 filebuf class................................... 4-14 fstream class................................... 4-19 IAPP(TYPE) class................................ 4-22 ifstream class.................................. 4-24 IMANIP(TYPE) class.............................. 4-27 IOAPP(TYPE) class............................... 4-29 IOMANIP(TYPE) class............................. 4-31 ios class....................................... 4-33 iostream class.................................. 4-46 iostream_withassign class....................... 4-48 istream class................................... 4-50 iii istream_withassign class........................ 4-58 istrstream class................................ 4-60 OAPP(TYPE) class................................ 4-62 ofstream class.................................. 4-64 OMANIP(TYPE) class.............................. 4-67 ostream class................................... 4-69 ostream_withassign class........................ 4-74 ostrstream class................................ 4-76 SAPP(TYPE) class................................ 4-78 SMANIP(TYPE) class.............................. 4-79 stdiobuf class.................................. 4-81 stdiostream class............................... 4-84 streambuf class................................. 4-87 strstream class................................. 4-99 strstreambuf class.............................. 4-101 5 Messages Package Messages class.................................. 5-2 6 Mutex Package Mutex class..................................... 6-2 7 Objection Package Global Declaration.............................. 7-2 Objection class................................. 7-3 8 Stopwatch Package Stopwatch class................................. 8-2 iv 9 String Package String class.................................... 9-2 10 task Package Global Declarations............................. 10-3 erand class..................................... 10-7 histogram class................................. 10-9 Interrupt_handler class......................... 10-12 object class.................................... 10-16 qhead class..................................... 10-20 qtail class..................................... 10-26 randint class................................... 10-31 sched class..................................... 10-33 task class...................................... 10-39 timer class..................................... 10-45 urand class..................................... 10-49 11 vector Package stack(TYPE) class............................... 11-3 vector(TYPE) class.............................. 11-7 Index Figures 4-1 Inheritance Diagram for the iostream Package....................................... 4-2 10-1 Inheritance Diagram for the task Package ..... 10-1 v Tables 1 Conventions Used in this Manual .............. ix vi ________________________________________________________________ Preface This manual describes the library of classes supplied with C++ Version 5.6 for OpenVMS systems. It contains detailed information on members of these classes (including member functions) and information on other associated functions, variables, and macros. Intended Audience This manual is intended for experienced programmers who have a basic understanding of the C++ language, and who are using C++ with the OpenVMS operating system in either a single or multiple platform environment. Some familiarity with the operating system is assumed. Document Structure This manual consists of an introductory chapter and 10 chapters describing each of the packages of predefined classes supplied with the C++ compiler. Associated Documents The following documents contain information related to this manual: o Using Compaq C++ for OpenVMS VAX This manual supplies information needed to use C++ on OpenVMS systems. o Stroustrup, Bjarne. Stroustrup, The C++ Programming Language, 3nd Edition, Addison-Wesley, 1997. Reading, Massachusetts. Addison-Wesley, 1997. vii This text combines a user guide and language reference manual. o Stroustrup, Bjarne and Margaret Ellis. The Annotated C++ Reference Manual. Reading, Massachusetts. Addison- Wesley, 1990. This text contains the current language definition of C++. viii o C Run-Time Library Reference Manual for OpenVMS Systems This manual describes C run-time library routines that are supported for C++. o Compaq C++ Installation Guide for OpenVMS VAX This guide supplies information needed to ensure that the C++ Class Library installs correctly on OpenVMS systems and is accessible to the C++ compiler. Conventions Table 1 lists the conventions used in this manual. Table_1_Conventions_Used_in_this_Manual___________________ Conventions_____________Meaning___________________________ class complex { A vertical ellipsis indicates that . some intervening program code or . output is not shown. Only the more . pertinent material is shown in the }; example. , . . . A horizontal ellipsis in a syntax description indicates that you can enter additional parameters, options, or values. A comma preceding the ellipsis indicates that successive items must be separated by commas. The complex class . . . Monospaced type denotes the names of C++ language elements, and also The get() func- the names of classes, members, tion . . . and nonmembers. Monospaced type is also used in text to reference code elements displayed in examples. (continued on next page) ix Table_1_(Cont.)_Conventions_Used_in_this_Manual___________ Conventions_____________Meaning___________________________ italic Italic type denotes the names of variables that appear as parameters or in arguments to functions. boldface Boldface type in text indicates the first instance of terms ________________________defined_in_text.__________________ Reader's Comments You may send your comments or suggestions regarding this manual, or any C++ document, by electronic mail to the following Internet address: cxx_docszko.dec.com x 1 ________________________________________________________________ Overview The C++ Class Library is a set of headers and other files implementing a collection of basic C++ classes. In the library, these classes are arranged in functionally related groups called packages. The DEC C++ Class Library makes use of other run-time libraries. ________________________Note ________________________ Identifiers beginning with cxxl or CXXL are reserved for the DEC C++ Class Library and should not be used by customer programs except as specified in this manual. Error message examples in this manual are displayed without their OpenVMS facility, error severity, or message identification code prefixes. You can achieve this result by entering the following DCL command: $ set message/nofac/nosev/noid _____________________________________________________ 1.1 Thread Safe Programming Developers of multithreaded applications should note the following: o Internal class library data is thread safe; multiple threads can access the DEC C++ Class Library simul- taneously without compromising the integrity of the internal data. Overview 1-1 Overview 1.1 Thread Safe Programming o The predefined stream objects, cerr, cin, clog, and cout are thread safe. However, you need to provide synchronization around sequences of operations on these objects. For more information on synchronizing access to the predefined stream objects, see Chapter 4. o User-defined objects are not thread safe; users must provide synchronization for such objects if they are shared between threads. For more information on synchronizing access to user-defined objects, see Chapter 6. o The ios class member function sync_with_stdio() is not thread safe; if your application calls this function, the call must come before any threads use the predefined stream objects: cerr, cin, clog, or cout. o Generation of error messages within the vector package is not thread safe; the package uses static data members to handle the current error message and there is no synchronization between threads. Digital recommends that you define a single Mutex object to synchronize all use of the vector package. o The task package is not thread safe; only one task can execute at a time. 1-2 Overview 2 ________________________________________________________________ complex Package The complex package provides ways to perform arithmetical operations, such as initialization, assignment, input, and output, on complex values (that is, numbers with a real part and an imaginary part). Additionally, this package supports operations that are unique to complex values, such as principal argument operations, conjugate operations, and conversions to and from polar coordinates. With the c_exception class and its c_exception function, the complex package also provides a mechanism for reporting and handling complex arithmetical errors. complex Package 2-1 Global Declarations ________________________________________________________________ Global Declarations These declarations are used by the complex package but they are not members of the complex class. Header #include Alternative Header #include Declarations typedef int (*cxxl_p_complex_error_t)(c_exception &error_information); static const complex_zero (0, 0); cxxl_p_complex_error_t set_complex_error(cxxl_p_complex_error_t p_complex_error); Type cxxl_p_complex_error_t Is the type of the complex_error function. Data static const complex_zero (0, 0) Is a constant object of type complex and value 0 created in each module that uses the complex package. Function cxxl_p_complex_error_t set_complex_error (cxxl_p_complex_ error_t p_complex_error) Causes the function pointed to by p_complex_error to be called instead of the complex_error function on subsequent complex arithmetical errors. If set_complex_error() previously has not been called, then it returns 0; otherwise, it returns the address of the last function passed to it. 2-2 complex Package Global Declarations See the Other Function section of c_exception class for a description of the error-handling function. complex Package 2-3 complex class ________________________________________________________________ complex class Provides a representation of, and lets you perform operations on, complex values. Header #include Alternative Header #include Declaration class complex { friend complex polar(double, double = 0); friend double abs(const complex &); friend double norm(const complex &); friend double arg(const complex &); friend double arg1(const complex &); friend complex conj(const complex &); friend complex sin(const complex &); friend complex sinh(const complex &); // c_exception OVERFLOW friend complex cos(const complex &); friend complex cosh(const complex &); // c_exception OVERFLOW friend complex tan(const complex &); friend complex tanh(const complex &); friend double imag(const complex &); friend double real(const complex &); friend complex log(const complex &); // c_exception SING // c_exception OVERFLOW UNDERFLOW friend complex exp(const complex &); friend complex pow(double, const complex &); friend complex pow(const complex &, int); friend complex pow(const complex &, double); friend complex pow(const complex &, const complex &); friend complex sqrt(const complex &); friend complex sqr(const complex &); friend complex operator-(const complex &); friend complex operator+(const complex &, const complex &); 2-4 complex Package complex class friend complex operator-(const complex &, const complex &); friend complex operator*(const complex &, const complex &); friend complex operator/(const complex &, const complex &); friend int operator==(const complex &, const complex &); friend int operator!=(const complex &, const complex &); friend ostream &operator<<(ostream &, const complex &); friend istream &operator>>(istream &, complex &); public: complex(double, double = 0); complex(); inline complex &operator-=(const complex &); inline complex &operator+=(const complex &); complex &operator*=(const complex &); complex &operator/=(const complex &); }; Description This class contains methods to perform complex value operations. These include arithmetical, assignment, and comparison operators for complex values; Cartesian and polar coordinates; mixed-mode arithmetic; and mathematical functions for complex values equivalent to standard mathematical functions. Exception Handling When a complex arithmetical error is detected, a c_ exception object is created with one of the following values for type: __________________________________________________________ Value________Error_Description____________________________ OVERFLOW Value too large to be represented SING Function undefined for argument UNDERFLOW____Value_too_small_to_be_represented____________ This object is then passed to the complex_error function (see the c_exception class). complex Package 2-5 complex class Constructors and Destructors complex() Constructs and initializes a complex value to 0. complex(double x, double y = 0) Constructs and initializes a complex value from Cartesian coordinates. Overloaded Operators complex operator + (const complex &z1, const complex &z2) Returns the arithmetical sum of the complex values z1 and z2. complex operator - (const complex &z1) Returns the arithmetical negation of a complex value. complex operator - (const complex &z1, const complex &z2) Returns the arithmetical difference of complex values. That is, z2 is subtracted from z1. complex operator * (const complex &z1, const complex &z2) Returns the arithmetical product of the complex values z1 and z2. complex operator / (const complex &z1, const complex &z2) Returns the arithmetical quotient of complex values. That is, z1 is divided by z2. inline complex &operator += (const complex &z1) Assigns the arithmetical sum of complex values to the complex object on the left side of an equation. That is, z1+=z2 is equivalent to z1=z1+z2. inline complex &operator -= (const complex &z1) Assigns the arithmetical difference of two complex numbers to the complex object on the left side of an equation. That is, z1-=z2 is equivalent to z1=z1-z2. 2-6 complex Package complex class complex &operator *= (const complex &z2) Assigns the arithmetical product of two complex numbers to the complex object on the left side of an equation. That is, z1*=z2 is equivalent to z1=z1*z2. complex &operator /= (const complex &z2) Assigns the arithmetical quotient of two complex numbers to the complex object on the left side of an equation. That is, z1/=z2 is equivalent to z1=z1/z2. ostream &operator << (ostream &s, const complex &z1) Sends a complex value to an output stream in the format (real,imag). It returns the left argument s. istream &operator >> (istream &s, complex &z1) Takes a complex value from an input stream. The numbers may be of the forms (real,imag) or (real), where real and imag are what the iostream library accepts for parameters of type double. The iostream library also determines how to handle white space. This operator returns the left argument s. The following input format omissions will cause an error: o Parenthesis missing before a complex value o Comma missing before the imaginary part of a complex value, if any o Parenthesis missing after the complex value int operator == (const complex &z1, const complex &z2) Compares two complex values and returns a nonzero value if the two numbers are equal; otherwise, it returns 0. int operator != (const complex &z1, const complex &z2) Compares two complex values and returns a nonzero value if the two numbers are not equal; otherwise, it returns 0. complex Package 2-7 complex class Other Functions double abs(const complex &z1) Returns the absolute value (magnitude) of a complex value. double arg(const complex &z1) Returns the angle, in radians, of a complex value. The result is normalized such that it is greater than or equal to 0, and less than 2*. double arg1(const complex &z1) Returns the principal value of the angle, in radians, of a complex value. The result is normalized such that it is greater than -, and less than or equal to . complex conj(const complex &z1) Returns the conjugate of a complex value; that is, if the number is (real, imag), then the result is (real, -imag). complex cos(const complex &z1) Returns the cosine of a complex value. complex cosh(const complex &z1) Returns the hyperbolic cosine of a complex value. The value of real(z1) must be small enough so that exp(real(z1)) does not overflow; otherwise, the function creates a c_exception object and invokes the complex_error function. complex exp(const complex &z1) Returns the value of e (2.71828...) raised to the power of a complex value. The conditions described for cosh() must be met; otherwise, it creates a c_exception object and invokes the complex_error function. double imag(const complex &z1) Returns the imaginary part of a complex value. complex log(const complex &z1) Returns the natural logarithm (base e, 2.71828...) of a complex value. The conditions described for cosh() must 2-8 complex Package complex class be met; otherwise, it creates a c_exception object and invokes the complex_error function. double norm(const complex &z1) Returns the square of the absolute value (magnitude) of a complex value. complex polar(double rho, double theta = 0) Creates a complex value given a pair of polar coordinates (magnitude rho and angle theta, in radians). complex pow(const complex &z1, int i2) Returns the value of z1 raised to the power of i2. complex pow(const complex &z1, double x2) Returns the value of z1 raised to the power of x2. complex pow(double z1, const complex &z2) Returns the value of z1 raised to the power of z2. complex pow(const complex &z1, const complex &z2) Returns the value of z1 raised to the power of z2. double real(const complex &z1) Returns the real part of a complex value. complex sin(const complex &z1) Returns the sine of a complex value. complex sinh(const complex &z1) Returns the hyperbolic sine of a complex value. The conditions described for cosh() must be met; otherwise, it creates a c_exception object and invokes the complex_ error function. complex sqr(const complex &z1) Returns the square of a complex value. complex sqrt(const complex &z1) Returns the square root of a complex value. complex tan(const complex &z1) Returns the tangent of a complex value. complex Package 2-9 complex class complex tanh(const complex &z1) Returns the hyperbolic tangent of a complex value. The conditions described for cosh() must be met; otherwise, it creates a c_exception object and invokes the complex_ error function. Examples 1. complex zz(3,-5); Declares zz to be a complex object and initializes it to the value of real part 3 and imaginary part -5. 2. complex myarray[30]; Declares an array of 30 complex objects, all initial- ized to (0,0). 3. complex zz; while (!(cin >> zz).eof()) cout << zz << endl; Reads a stream of complex values [for example, (3.400000,5.000000)] and writes them in the default format [for example, (3.4, 5)]. 4. complex cc = complex (3.4,5); cout << real(cc) << "+" << imag(cc) << "*i"; Prints out 3.4 as the real part of a complex object and 5 as the imaginary part. The result is 3.4+5*i. 2-10 complex Package c_exception class ________________________________________________________________ c_exception class Contains information on a complex arithmetical exception. Header #include Alternative Header #include Declaration class c_exception { friend complex exp(const complex &); friend complex sinh(const complex &); friend complex cosh(const complex &); friend complex log(const complex &); friend int complex_error(c_exception &); public: int type; char *name; complex arg1; complex arg2; complex retval; public: c_exception(char *, const complex &, const complex & = complex_zero); }; Description Objects of this class handle exceptions for complex arithmetic. This includes information on functions, parameters, error types, and default return values. complex Package 2-11 c_exception class Data Members complex arg1 Is the left argument of the function that incurred the error. complex arg2 Is the right argument of the function that incurred the error. char *name Is the name of the function that incurred the error. complex retval Is the value to be returned by the function that incurred the error. You may use the complex_error(c_exception &) function to change this value. int type Is one of these kinds of error: SING, OVERFLOW, or UNDERFLOW. Constructor c_exception(char *function_name, const complex &function_ arg1, const complex &function_arg2 = complex_zero) Constructs a complex arithmetical exception object, with reference to the name and arguments of the function that incurred the error. Other Function int complex_error (c_exception &error_information) Is the default error-handling function that is called by certain complex arithmetical functions in this package (namely, cosh, exp, log, and sinh) when those functions detect an arithmetical error. You may replace this function with your own function that takes an identical parameter list and returns a value as specified in the following table: 2-12 complex Package c_exception class __________________________________________________________ Return Value from Error-handling Action Taken by Complex Arithmetical Function______________Function____________________________ 0 Set the global value errno; if the error type is SING, print an error message. non 0 Do not set errno; do not print an ______________________error_message.______________________ To substitute your own error-handling function, pass a pointer to your function to the set_complex_error function. (See the Function section under Global Declarations for the complex package.) The complex arithmetical functions that invoke the error handling function always return the value specified in error_information.retval. Your error-handling function may set this value. complex Package 2-13 3 ________________________________________________________________ generic Package The generic package provides ways to simulate parame- terized types by allowing the instantiation of class declarations using the macro facilities of the C++ preprocessor. You can use the generic package to construct container classes. The actual types of the data members are passed at compile time as parameters to the class when you use the class name. To declare a generic type: 1. Define a name for the class and specify the number of type parameters: #define YOUR_CLASS_NAME(TYPE_PARAMETER_NAME) name2(TYPE_PARAMETER_NAME, YOUR_CLASS_NAME) To specify two type parameters, use the name3 macro. 2. Define the class body as a macro: #define YOUR_CLASS_NAMEdeclare(TYPE_PARAMETER_NAME) class { . . . }; #define YOUR_CLASS_NAMEimplement(TYPE_PARAMETER_NAME) . . . 3. Declare the actual class: declare(YOUR_CLASS_NAME, ACTUAL_TYPE_NAME) By substituting one or another class of ACTUAL_TYPE_ NAME, you can declare multiple instances of the generic class template with various component types. For example, depending on the type parameter you use, you can declare such types as list of ints, list of Strings, or list of lists of Strings. If it is not a type name, ACTUAL_TYPE_NAME must be a typedef name. generic Package 3-1 You must do this in each compilation unit that uses the parameterized type with a given parameter. 4. Define the functions or static data of the actual class. implement(YOUR_CLASS_NAME, ACTUAL_TYPE_NAME) You must do this once in each program that uses the parameterized type with a given parameter. 5. Declare an instance of the class you have declared by specifying objects of type YOUR_CLASS_NAME(ACTUAL_TYPE_ NAME), as follows: YOUR_CLASS_NAME(ACTUAL_TYPE_NAME) object1, object2; 3-2 generic Package Global Declarations ________________________________________________________________ Global Declarations These declarations are used by the generic package but they are not members of any class. Header #include Alternative Header #include Compile-Time Parameters TYPE, TYPE1, TYPE2-The types for which this class is parameterized; TYPE, TYPE1, or TYPE2 must be an identifier. CLASS-The class that is parameterized. For a vector of integers, for example, CLASS is vector and TYPE is int. Declarations typedef int (*GPT)(int, char *); int genericerror(int n, char *msg); Type GPT Is a pointer to a generic error-handling function. Function int genericerror (int n, char *msg) Is the default error-handling function; it prints an error number (n) and message (msg) on cerr and calls abort(). Macros Macros provide preprocessor facilities for simulating parameterized types. The following macros are defined for the generic package: generic Package 3-3 Global Declarations callerror(CLASS, TYPE, N, S) Calls the current error handler for a given instance of a parameterized class. CLASS denotes the name of the generic class (for example, vector). TYPE denotes the type parameter for which to instantiate the generic class (for example, int to get a vector of integers); the type must be an identifier (for example, char* is not valid). N denotes the first argument to pass to the error handler; the default is the function genericerror(int, char*). S denotes the second argument to pass to the error handler. declare(CLASS, TYPE) Declares the class specified by a macro with the name of the generic class. The word declare follows the class name (for example, vectordeclare). It also defines the inline member functions of the class. CLASS denotes the name of the generic class (for example, vector). TYPE denotes the type parameter for which to instantiate the generic class (for example, int to get a vector of integers). The type must be an identifier (for example, char* is not valid). declare2(CLASS, TYPE1,TYPE2) Declares the class specified by a macro with the name of the generic class. The name is followed by the word declare2. The declare2 macro differs from the declare macro only in that you use it to declare two type parameters, TYPE1 and TYPE2. errorhandler(CLASS, TYPE) Is the name of the pointer to the error handler for a given instance of a parameterized class (for example, intvectorhandler to handle errors for a vector of integers). CLASS denotes the name of the generic class (for example, vector). TYPE denotes the type parameter for which to instantiate the generic class (for example, int to get a vector of integers). The type must be an identifier (for example, char* is not valid). implement(CLASS, TYPE) Defines the noninline member functions of a class, specified by a macro with the name of the generic class. The name is followed by the word implement (for example, 3-4 generic Package Global Declarations vectorimplement). The implement macro takes the same arguments as the declare macro. implement2(CLASS, TYPE1,TYPE2) Defines the noninline member functions of a class, specified by a macro with the name of the generic class. The name is followed by the word implement2. The implement2 macro differs from the implement macro only in that you use it to declare two type parameters, TYPE1 and TYPE2. name2(S1,S2) Concatenates two identifier segments to form a new identifier using the ## operator. name3(S1,S2,S3) Concatenates three identifier segments to form a new identifier using the ## operator. name4(S1,S2,S3,S4) Concatenates four identifier segments to form a new identifier using the ## operator. set_handler(CLASS, TYPE, HANDLER) Specifies a function as the current error handler for a given instance of a parameterized class. Initially, the error-handling function is set to genericerror(int, char*). CLASS denotes the name of the generic class (for example, vector). TYPE denotes the type parameter for which to instantiate the generic class (for example, int to get a vector of integers); the type must be an identifier (for example, char* is not valid). HANDLER denotes a pointer to the function you want to set to the new error handler. Also, you can use the set_handler macro in a function declaration or definition. generic Package 3-5 Global Declarations Example The following program shows the use of the genericerror function and associated macros: extern "C" { #include #include #include } #include #define my_vector(T) name2(T, my_vector) // Declare a vector of objects of type T (the class and extern data) #define my_vectordeclare(T) \ class my_vector(T) \ { \ private: \ int s; \ T *p; \ public: \ my_vector(T)(int); \ ~my_vector(T)(); \ T &operator[](int); \ }; \ extern GPT errorhandler(my_vector, T); \ extern GPT set_handler(my_vector, T, GPT); 3-6 generic Package Global Declarations // Implement a vector of objects of type T // (Define the functions and global data) #define my_vectorimplement(T) \ my_vector(T)::my_vector(T)(int size) \ { \ s = size; \ p = new T[size]; \ } \ my_vector(T)::~my_vector(T)() \ { \ delete[] p; \ } \ T &my_vector(T)::operator[](int i) \ { \ if(i < 0 || i >= s) \ { \ callerror(my_vector, T, i, "Index out of bounds"); \ static T error_object; \ return error_object; \ } \ return p[i]; \ } \ GPT errorhandler(my_vector, T) = &genericerror; \ GPT set_handler(my_vector, T, GPT new_genericerror) \ { \ GPT old_genericerror = errorhandler(my_vector, T); \ errorhandler(my_vector, T) = new_genericerror; \ return old_genericerror; \ } // Declare and implement vector of int declare(my_vector, int) implement(my_vector, int) // Error-handling function my_handler( int n, char *msg ) generic Package 3-7 Global Declarations { fflush(stderr); printf("in my_handler(%d,\"%s\")\n", n, msg); fflush(stdout); return 0; } int main(int argc, char *argv[]) { my_vector(int) v1(10); GPT old_error_handler; // Set the handler to a function that does not abort old_error_handler = set_handler(my_vector, int, &my_handler); v1[12345] = 0; // Restore the handler and cause an error // This should abort old_error_handler = set_handler(my_vector, int, old_error_handler); v1[12345] = 0; return EXIT_SUCCESS; } See Also vector Package 3-8 generic Package 4 ________________________________________________________________ iostream Package Classes in the iostream package provide methods to handle input and output streams, including reading and writing built-in data types. You also can extend certain methods described here to handle class types. This package includes, among others, the classes ios and streambuf, and the subclasses derived from these base classes. Figure 4-1 shows the inheritance structure of the iostream package. In the diagram, arrows point from the base classes to derived classes. The istream (input stream) class supports input operations (extractions); the ostream (output stream) class supports output operations (insertions). The iostream class derives from both istream and ostream, and supports both extractions and insertions. The following stream objects are predefined: cin An istream_withassign object linked to standard input cout An ostream_withassign object linked to standard output cerr An ostream_withassign object linked to standard error that supports unbuffered output clog An ostream_withassign object linked to standard error that supports buffered output To generate output, you apply the insertion operator (<<) to cout, as shown in the following example: cout << "Hello\n" ; iostream Package 4-1 Figure 4-1 Inheritance Diagram for the iostream Package Obtaining input is similar to generating output, except that you apply the extraction operator (>>) to cin, as shown in the following example: int eye, jay ; cin >> eye >> jay ; If you include these fragments of code in a program, your system expects users to type in two integer values (for eye and jay) from a terminal. The iostream package supplies predefined extraction and insertion operators for all built-in data types, including char*. This package also supports file manipulation. To connect a specific file to your program, instantiate one of the following class types: 4-2 iostream Package ifstream (for file input) ofstream (for file output) fstream (for both input and output) To format within character arrays, the iostream package includes the following associated class types: istrstream (for fetching characters from an array) ostrstream (for storing characters into an array) strstream (for both fetching and storing characters into an array) ________________________Note ________________________ On systems with IEEE floating-point arithmetic, certain values may be printed as symbols for Infinity (for example, INF) or Not a Number (for example, NaN). _____________________________________________________ Deriving Your Own Class from ios If you derive your own class from the ios class, or from one of its derived classes, the ios subobject must be initialized properly during instantiation. Specifically, you must ensure that the streambuf pointer within the ios subobject is valid. To do this, you can specify the ios(streambuf *) construc- tor as a member initializer for your class constructor. Optionally, you can call the ios::init(streambuf *) member function. Thread Safety The predefined stream objects, cerr, cin, clog, and cout are thread safe only for individual calls into the DEC C++ Class Library. You must provide synchronization around sequences of calls. For more information on synchronizing access to predefined stream objects, see the section on Global Declarations in this chapter. User-defined stream objects are not thread safe, so you must provide synchronization around individual calls as well as sequences of calls. For more information on synchronizing access to user-defined objects, see iostream Package 4-3 Chapter 6 and the section on Global Declarations in this chapter. The ios member function sync_with_stdio() is not thread safe. If your application calls this function, it must make the call before any threads use cerr, cin, clog, or cout. 4-4 iostream Package Global Declarations ________________________________________________________________ Global Declarations These declarations are used by the iostream package but they are not members of any class. Header #include Alternative Header #include Declarations typedef long streamoff typedef long streampos ios &dec(ios &s); ios &hex(ios &s); ios &oct(ios &s); ios &lock(ios &s); ios &unlock(ios &s); istream &ws(istream &i); ostream &endl(ostream &o); ostream &ends(ostream &o); ostream &flush(ostream &o); Types typedef long streamoff Is the type representing a character offset into a stream. For more information, see the description of the seekoff and seekpos functions in the streambuf class. typedef long streampos Is the type representing a character position in a stream. For more information, see the description of the seekoff and seekpos functions in the streambuf class. iostream Package 4-5 Global Declarations Manipulators The following functions insert values into a stream, extract values from a stream, or specify the conversion base format. For more information on the conversion base format flags, see the ios class. ios &dec(ios &s) Sets the conversion base format for s to decimal, essentially clearing the ios::oct and ios::hex flags and setting the ios::dec flag. ios &hex(ios &s) Sets the conversion base format for s to hexadecimal, essentially clearing the ios::oct and ios::dec flags and setting the ios::hex flag. ios &oct(ios &s) Sets the conversion base format for s to octal, es- sentially clearing the ios::dec and ios::hex flags and setting the ios::oct flag. istream &ws(istream &i) Extracts (skips) white-space characters from i. ostream &endl(ostream &o) Ends a line by inserting a new-line character into o and flushing o. ostream &ends(ostream &o) Ends a string by inserting a null '/0' character into o. ostream &flush(ostream &o) Flushes o. Synchronizing Access to Predefined Stream Objects The following unparameterized manipulators are for use in synchronizing access to the predefined stream objects, cerr, cin, clog, and cout: 4-6 iostream Package Global Declarations ios &lock(ios &s) Locks s if s is one of the predefined stream objects. ios &unlock(ios &s) Unlocks s if s is one of the predefined stream objects. If your application needs to lock two or more of these objects at the same time, your application must adhere to the following locking order: iostream Package 4-7 Global Declarations 1. cin 2. cerr 3. clog 4. cout For example, if your application needs to lock both cerr and cout, lock cerr first and cout second. The unlocking order is not important. Keep in mind that when your application calls a member function for a predefined stream object, the member function will typically lock the object for the duration of the call. Therefore, if your application has locked one of the stream objects and then uses another, this use must also adhere to the predefined locking order. For example, your application should not send output to cerr while cout is locked. The locking order necessarily matches the default ties between the stream objects as follows: cin is tied to cout cerr is tied to cout clog is tied to cout cout has no ties Any input/output operation on a stream object causes the iostream package to flush the object to which it is tied. Thus, an output to cerr flushes cout. Examples 1. #include #include int main () { int value = 10; cout << hex << value << ','; // Change the base conversion format to // hexadecimal; note that the default is // decimal as set by the ios constructors. cout << value << ','; // The base conversion format set in the // previous line is still active. 4-8 iostream Package Global Declarations cout << dec << value << endl; // Change the base conversion format to // decimal; lastly, insert a new-line // character into the stream and flush // cout. return 0; } The output is a,a,10. 2. #include #include void print_name(String &name) { cout << lock << "Hello, " << name << endl << unlock; } This synchronizes access to the cout object so that the "Hello, ", name, and new-line character are written to cout as a single unit. If you do not use the lock and unlock manipulators in this example, another thread could possibly insert its own text into cout in the midst of your output. iostream Package 4-9 Global Declarations Header #include Alternative Header #include Declarations SMANIP(long) resetiosflags(long); SMANIP(long) setiosflags(long); SMANIP(int) setfill(int); SMANIP(int) setprecision(int); SMANIP(int) setw(int w); SMANIPREF(Mutex) lock(Mutex &m) SMANIPREF(Mutex) unlock(Mutex &m) Functions These functions are used for extending the iostream package with user-defined parameterized manipulators. SMANIP(long) resetiosflags(long x) In the stream (ios or a stream derived from ios), clears the format flags denoted by x. SMANIP(int) setfill(int x) Sets the fill character to be the value specified by x. The fill character is a data member of the ios class; however, setting it with this function affects only output streams. SMANIP(long) setiosflags(long x) In the stream (ios or a stream derived from ios), turns on the format flags denoted by x. If you are setting a flag that is part of a collection (for example, basefield), note that this manipulator does not clear the other flags in the collection. 4-10 iostream Package Global Declarations SMANIP(int) setprecision(int x) Sets the variable that controls the number of digits inserted by the floating-point inserter to be x. This variable is a data member of the ios class; however, setting it with this function affects only output streams. SMANIP(int) setw(int w) In the stream (ios or a stream derived from ios), sets the field width of the stream to w. Synchronizing Access to User-Defined Stream Objects The following parameterized manipulators are for use in synchronizing access to user-defined stream objects. To use these manipulators, you must first define a Mutex object, which you then pass to the manipulator. The association of a Mutex object with a stream object is not enforced by the iostream package. This association is enforced only by you, the programmer. Refer to Chapter 6 for information on the Mutex class. SMANIPREF(Mutex) lock(Mutex &m) Locks the recursive Mutex represented by m. SMANIPREF(Mutex) unlock(Mutex &m) Unlocks the recursive Mutex represented by m. Examples 1. char c; cin >> resetiosflags(ios::skipws) >> c >> setiosflags(ios::skipws); Turns off the flag (resets it to 0) that tells the extractor (>>) to skip leading white space and then turns that flag back on again (sets it to 1). iostream Package 4-11 Global Declarations 2. cout.fill(*) cout.setf(ios::left,ios::adjustfield); cout << setw(6) << 23 << "," ; cout.fill(%); cout.setf(ios::right,ios::adjustfield); cout << setw(4) << 34 << "\n" ; Places padding characters (specified by the fill state variable) after the first number and before the second number. The output is 23****,%%34. 3. #include #include #include #include main () { String name("Henry"); void print_name (String &, ostream &, Mutex &); ofstream mystream(1); Mutex mystream_lock; print_name(name, mystream, mystream_lock); return 0; } void print_name(String &name, ostream &stream, Mutex &stream_lock) { stream << lock(stream_lock) << "Hello, " << name << endl << unlock(stream_lock); } This example associates a Mutex object with a stream object to synchronize access to the stream. The Mutex is locked before using the stream and then unlocked afterwards. For the synchronization to work properly, each thread that uses this stream must perform the same lock/unlock sequence with the same Mutex. 4-12 iostream Package Global Declarations See Also IMANIP(TYPE) class IOMANIP(TYPE) class OMANIP(TYPE) class SMANIP(TYPE) class iostream Package 4-13 filebuf class ________________________________________________________________ filebuf class Provides a data buffer abstraction for input/output facilities through file descriptors. Header #include Alternative Header #include Declaration class filebuf: public streambuf { public: static const int openprot; filebuf(); filebuf(int fd); filebuf(int fd, char *p, int len); ~filebuf(); filebuf *attach(int fd); filebuf *close(); int fd(); int is_open(); filebuf *open(const char *name, int mode, int prot = openprot); virtual int overflow(int = EOF); virtual streampos seekoff(streamoff, seek_dir, int mode); virtual streampos seekpos(streampos, int mode); virtual streambuf *setbuf(char *p, int len); virtual int sync(); virtual int underflow(); }; 4-14 iostream Package filebuf class Description This class specializes the streambuf class to use a file as a repository of characters. Writing to the file consumes characters; reading from the file produces characters. Files that allow searches are said to be seekable. When a file is readable and writable, the filebuf object permits character insertion and extraction. If your program expects a buffer to be allocated when none was allocated, then the iostream package allocates a default buffer with a length specified by BUFSIZ as defined in stdio.h. The package then issues the following warning: Warning; a null pointer to streambuf was passed to ios::init() Data Member const int openprot = 0644 Provides default protection for the open() function. (For an explanation of the file protection, see the C Run-Time Library Reference Manual.) Constructors and Destructors filebuf() Constructs a filebuf object that is initially closed. filebuf(int fd) Constructs a filebuf object connected to file descriptor fd. filebuf(int fd, char *p, int len) Constructs a filebuf object connected to file descriptor fd, which is initialized to use the reserve area (buffer) starting at p and containing len bytes. ~filebuf() Deletes a filebuf object. iostream Package 4-15 filebuf class Member Functions filebuf *attach(int fd) Connects the filebuf object to an open file whose descriptor is passed through the fd argument. It normally returns a reference to the filebuf object, but returns 0 if the filebuf object is connected to an open file. filebuf *close() Flushes any waiting output, closes the file descriptor, and disconnects a filebuf object. Unless an error occurs, the filebuf object's error state will be cleared. The close() function returns the address of the filebuf object unless errors occur, in which case this function returns 0. Even if errors occur, close() leaves the file descriptor and filebuf object closed. int fd() Returns the file descriptor associated with a filebuf object. If the filebuf object is closed, fd returns EOF. int is_open() Returns a nonzero value when a filebuf object is connected to a file descriptor; otherwise, it returns 0. filebuf *open(const char *name, int mode, int prot) Opens a file with the name specified by name and connects a filebuf object to it. If the file does not exist, the function tries to create it with the protection mode prot unless ios::nocreate is specified in mode. By default, prot is filebuf::openprot. The function fails if the filebuf object is open. The open() function normally returns the address of the filebuf object, but returns 0 if an error occurs. The members of open_mode are bits that may be joined together by or (because this joining takes an int, open() takes an int rather than an open_mode argument). For an explanation of the meanings of these bits in open_mode, see the Enumerated Types section for the ios class. 4-16 iostream Package filebuf class virtual int overflow(int c) Called to consume characters in classes derived from streambuf. If c is not EOF, this function must also either save c or consume it. Although it can be called at other times, this function usually is called when the put area is full and an attempt is being made to store a new character. The normal action is to consume the characters between pbase() and pptr(), call setp() to establish a new put area, and (if c != EOF) store c using sputc(). A call to overflow(c) should return EOF to indicate an error; otherwise, it should return something else. virtual streampos seekoff(streamoff off, seek_dir dir, int mode) Moves the get pointer, put pointer, or both as designated by the off and dir arguments. It may fail if the file does not support seeking, or if the attempted motion is otherwise invalid (for example, attempting to seek a position before the beginning of the file). The off argument is interpreted as a count relative to the place in the file specified by dir. The mode argument is ignored. A call to seekoff() returns the new position or EOF if a failure occurs. After a failure, the position of the file is undefined. virtual streampos seekpos(streampos pos, int mode) Moves the file to a position pos. The mode argument is ignored. The function normally returns pos but it returns EOF on failure. virtual streambuf *setbuf(char *p, int len) Sets up the reserve area as the number of bytes specified in the second argument, beginning at the pointer specified in the first argument. If the pointer is null, or the number of bytes is less than 1, the filebuf object is unbuffered. This function normally returns a pointer to the filebuf object; however, if the filebuf object is open and a buffer is allocated, then no changes are made to the reserve area and to the buffering status, and setbuf() returns 0. iostream Package 4-17 filebuf class virtual int sync() Tries to get the state of the get pointer, the put pointer, or both, to agree (synchronize) with the state of the file to which the filebuf object is connected. This means that the function may write characters to the file if some of the characters have been buffered for output, or the function may try to reposition (seek) the file if characters have been read and buffered for input. Normally sync() returns 0, but it returns EOF if synchronization is not possible. When certain characters must be written together, the program should use setbuf() (or a constructor) to ensure that the reserve area is at least as large as the number of characters to be written together. Your program can then call sync(), store the characters, and then call sync() once again. virtual int underflow() Called in classes derived from streambuf to supply characters for fetching; that is, to create a condition in which the get area is not empty. If the function is called when characters occupy the get area, it should create a nonempty area and return the next character (which it should also leave in the get area). If no more characters are available, underflow() should return EOF and leave an empty get area. See Also ios class streambuf class 4-18 iostream Package fstream class ________________________________________________________________ fstream class Supports formatted and unformatted input from and output to files. Header File #include Alternative Header #include Declaration class fstream: public iostream { public: fstream(); fstream(const char *name, int mode, int prot = filebuf::openprot); fstream(int fd); fstream(int fd, char *p, int len); ~fstream(); void attach(int fd); void close(); void open(const char *name, int mode, int prot = filebuf::openprot) ; filebuf *rdbuf(); void setbuf(char *p, int len); }; Description This class specializes the iostream class to files by using a filebuf object to do the input and output. Your program can perform common operations, such as opening and closing files, without explicitly mentioning filebuf objects. iostream Package 4-19 fstream class Constructors and Destructors fstream() Constructs an unopened fstream object. fstream(int fd) Constructs an fstream object connected to the file whose descriptor is passed through the fd argument. The file must be open. fstream(int fd, char *p, int len) Constructs an fstream object connected to a file whose descriptor is passed through the fd argument, and also initializes the associated filebuf object to use the len bytes starting at p as the reserve area. If p is null or len is 0, the filebuf object is unbuffered. fstream(const char *name, int mode, int prot) Constructs an fstream object and opens the file specified by the name argument. The mode and prot arguments specify the file open mode and protection. By default, prot is filebuf::openprot. If the open action fails, the error state (io_state) of the constructed fstream object indicates failure. ~fstream() Deletes an fstream object. Member Functions void attach(int fd) Connects an fstream object to a file whose descriptor is passed through the fd argument. A failure occurs when the fstream object is connected to a file, in which case ios::failbit is set in the filebuf object's error state. void close() Closes any associated filebuf object and consequently breaks the connection of the fstream object to the file. The error state of the fstream object is cleared except on failure. A failure occurs when the call to the filebuf object's close() function fails. 4-20 iostream Package fstream class void open(const char *name, int mode, int prot) Opens a file with the file name specified by name and connects the fstream object to it. If the file does not exist, the function tries to create it with the protection specified by the prot argument unless ios::nocreate is set. By default, prot is filebuf::openprot. Failure occurs if the fstream object is open or when the call to the filebuf object's open() function fails, in which case ios::failbit is set in the filebuf object error state. The members of open_mode are bits that may be joined together by or (because this joining takes an int, open() takes an int rather than an open_mode argument). For an explanation of the meanings of these bits in open_ mode, see the Enumerated Types section for the ios class. filebuf *rdbuf() Returns a pointer to the filebuf object associated with the fstream object. This function has the same meaning as ios::rdbuf(), but has a different type. void setbuf(char *p, int len) Calls the associated filebuf object setbuf() function to request space for a reserve area. A failure occurs if the filebuf object is open or if the call to rdbuf()->setbuf fails for any other reason. iostream Package 4-21 IAPP(TYPE) class ________________________________________________________________ IAPP(TYPE) class For an istream object, declares predefined parameterized applicators. Header File #include Alternative Header #include Compile-Time Parameter TYPE-The type of the istream object. It must be an identifier. Declaration class IAPP(TYPE) { public: IAPP(TYPE)(istream &(*f)(istream &, TYPE)); IMANIP(TYPE) operator()(TYPE a); }; Constructor IAPP(TYPE) (istream &(*f) (istream &, TYPE)) Creates an applicator; *f is the left operand of the insertion operator. Operator IMANIP(TYPE) operator () (TYPE a) Casts an object of type a into a manipulator function for an istream object. 4-22 iostream Package IAPP(TYPE) class See Also IMANIP(TYPE) class iostream Package 4-23 ifstream class ________________________________________________________________ ifstream class Supports formatted and unformatted input from files. Header File #include Alternative Header #include Declaration class ifstream: public istream { public: ifstream(); ifstream(const char *name, int mode = ios::in, int prot = filebuf::openprot); ifstream(int fd); ifstream(int fd, char *p, int len); ~ifstream(); void attach(int fd); void close(); void open(const char *name, int mode = ios::in, int prot = filebuf::openprot); filebuf *rdbuf(); void setbuf(char *p, int len); }; Description This class specializes the istream class to files by using a filebuf object to do the input. Your program can perform common operations, such as opening and closing files, without explicitly mentioning filebuf objects. 4-24 iostream Package ifstream class Constructors and Destructors ifstream() Constructs an unopened ifstream object. ifstream(int fd) Constructs an ifstream object connected to a file whose descriptor is passed through the fd argument. The file must already be open. ifstream(int fd, char *p, int len) Constructs an ifstream object connected to a file whose descriptor is passed through the fd argument, and also initializes the associated filebuf object to use the len bytes starting at p as the reserve area. If p is null or len is 0, the filebuf object is unbuffered. ifstream(const char *name, int mode, int prot) Constructs an ifstream object and opens the file with the file name specified by name. The mode and prot arguments specify the file open mode and protection. By default, prot is filebuf::openprot. If the open fails, the error state (io_state) of the constructed ifstream object indicates failure. ~ifstream() Deletes an ifstream object. Member Functions void attach(int fd) Connects an ifstream object to a file whose descriptor is passed through the fd argument. A failure occurs when the ifstream object is connected to a file, in which case ios::failbit is set in the ifstream object error state. void close() Closes any associated filebuf object and consequently breaks the connection of the ifstream object to the file. The error state of the fstream object is cleared except on failure. A failure occurs when the call to the filebuf object's close() function fails. iostream Package 4-25 ifstream class void open(const char *name, int mode, int prot) Opens a file specified by the name argument and connects the ifstream object to it. If the file does not exist, the function tries to create it with the protection specified by the prot argument unless ios::nocreate is set. By default, prot is filebuf::openprot. Failure occurs if the ifstream object is open or when the call to the filebuf object open() function fails, in which case ios::failbit is set in the filebuf object error state. The members of open_mode are bits that may be joined together by or (because this joining takes an int, open() takes an int rather than an open_mode argument). For an explanation of the meanings of these bits in open_ mode, see the Enumerated Types section for the ios class. filebuf *rdbuf() Returns a pointer to the filebuf object associated with the ifstream object. This function has the same meaning as ios::rdbuf() but has a different type. void setbuf(char *p, int len) Calls the associated filebuf object setbuf() function to request space for a reserve area. A failure occurs if the filebuf object is open or if the call to rdbuf()->setbuf fails for any other reason. 4-26 iostream Package IMANIP(TYPE) class ________________________________________________________________ IMANIP(TYPE) class For an istream object, declares the predefined parame- terized manipulators and provides macros for user-defined parameterized manipulators. Header File #include Alternative Header #include Compile-Time Parameter TYPE-The type of the istream object. It must be an identifier. Declaration class IMANIP(TYPE) { public: IMANIP(TYPE)(istream &(*f)(istream &, TYPE), TYPE a); friend istream &operator>>(istream &s, IMANIP(TYPE) &m); }; Description These manipulators serve the istream class by producing some useful effect, such as embedding a function call in an expression containing a series of insertions and extractions. You also can use manipulators to shorten the long names and sequences of operations required by the iostream class. In its simplest form, a manipulator takes an istream& argument, operates on it in some way, and returns it. iostream Package 4-27 IMANIP(TYPE) class Constructor IMANIP(TYPE)(istream &(*f)(istream &, TYPE), TYPE a) Creates a manipulator; *f is the left operand of the extractor operator. Operator istream &operator >> (istream &s, IMANIP(TYPE) &m) Takes data from an istream object. 4-28 iostream Package IOAPP(TYPE) class ________________________________________________________________ IOAPP(TYPE) class For an iostream object, declares predefined parameterized applicators. Header File #include Alternative Header #include Compile-Time Parameter TYPE-The type of the iostream object. It must be an identifier. Declaration class IOAPP(TYPE) { public: IOAPP(TYPE)(iostream &(*f)(iostream &, TYPE)); IOMANIP(TYPE) operator()(TYPE a); }; Constructor IOAPP(TYPE)(iostream &(*f)(iostream &, TYPE)) Creates an applicator. Operator IOMANIP(TYPE) operator () (TYPE a) Casts an object of type a into a manipulator function for an iostream object. iostream Package 4-29 IOAPP(TYPE) class See Also IOMANIP(TYPE) class 4-30 iostream Package IOMANIP(TYPE) class ________________________________________________________________ IOMANIP(TYPE) class For an iostream object, declares predefined parameterized manipulators and provides macros for user-defined parameterized manipulators. Header File #include Alternative Header #include Compile-Time Parameter TYPE-The type of the iostream object. It must be an identifier. Declaration class IOMANIP(TYPE) { public: IOMANIP(TYPE)(iostream &(*f)(iostream &, TYPE), TYPE a); friend istream &operator>>(iostream &s, IOMANIP(TYPE) &m); friend ostream &operator<<(iostream &s, IOMANIP(TYPE) &m); }; IOMANIPdeclare(int); IOMANIPdeclare(long); Description These manipulators serve the iostream class by producing some useful effect, such as embedding a function call in an expression containing a series of insertions and extractions. You can also use manipulators to shorten the long names and sequences of operations required by the iostream class. In its simplest form, a manipulator takes an iostream& argument, operates on it in some way, and returns it. iostream Package 4-31 IOMANIP(TYPE) class Two ios manipulators for using Mutex objects, lock and unlock, come in both parameterized and unparameterized forms. The parameterized manipulators let users synchro- nize iostream objects, the parameter being a user-defined Mutex object. To use parameterized manipulators, you must include iomanip.hxx. Unparameterized manipulators let users synchronize the predefined stream objects: cerr, cin, clog, and cout. For examples of using the lock and unlock manipulators, see Chapter 6 and the section on Global Declarations in this chapter. Constructor IOMANIP(TYPE)(iostream &(*f)(iostream &, TYPE), TYPE a) Creates a manipulator. Macro IOMANIPdeclare(TYPE) Declares the manipulators (and the manipulator classes) that have an operator() member function for type TYPE. Operators ostream &operator << (iostream &s, IOMANIP(TYPE) &m) Sends data to an iostream object. istream &operator >> (iostream &s, IOMANIP(TYPE) &m) Takes data from an iostream object. 4-32 iostream Package ios class ________________________________________________________________ ios class Contains state variables common to most of the other classes in the iostream package. Header #include Alternative Header #include Declaration class ios { public: enum io_state { goodbit = 0, eofbit = 01, failbit = 02, badbit = 04 }; enum open_mode { in = 01, out = 02, ate = 04, app = 010, trunc = 020, nocreate = 040, noreplace = 0100 }; enum seek_dir { beg = 0, cur = 01, end = 02 }; enum { skipws = 01, left = 02, right = 04, internal = 010, dec = 020, oct = 040, hex = 0100, showbase = 0200, showpoint = 0400, uppercase = 01000, showpos = 02000, scientific = 04000, fixed = 010000, unitbuf = 020000, stdio = 040000 }; static const long basefield; static const long adjustfield; static const long floatfield; ios(streambuf *); virtual ~ios(); iostream Package 4-33 ios class inline int bad() const; static long bitalloc(); inline void clear(int state = 0); inline int eof() const; inline int fail() const; inline char fill() const; char fill(char); inline long flags() const; long flags(long); inline int good() const; long &iword(int); inline int operator!(); inline operator void *(); inline int precision() const; int precision(int); void *&pword(int); inline streambuf *rdbuf(); inline int rdstate() const; long setf(long setbits, long field); long setf(long); static void sync_with_stdio(); inline ostream *tie() const; ostream *tie(ostream *); long unsetf(long); inline int width() const; int width(int n); static int xalloc(); protected: ios(); void init(streambuf *); inline void setstate(int state); }; Description Classes derived from the ios class provide an interface for transferring formatted and unformatted information into and out of streambuf objects. 4-34 iostream Package ios class Enumerated Types io_state Represents a collection of bits (flags) that describe the internal error states of an object. The values are as follows: goodbit No errors occurred. eofbit End-of-file encountered during an extraction operation. failbit Extraction or conversion failed but the stream is still usable. badbit A severe error, usually in an operation on the associated streambuf object, from which recovery is unlikely. open_mode Represents a collection of bits (flags) for specifying the mode of the open() function. Use this data type with objects of the fstream, ifstream, and ofstream classes. The values are as follows: app Performs a seek to the end-of-file. This appends to the end of the file any subsequent data written to the file. ios::app implies ios::out. ate Performs a seek to the end-of-file during an open() operation. ios::ate does not imply ios::out. in Opens the file for input. Constructions and open operations of ifstream objects imply ios::in. For fstream objects, ios::in signifies that input operations should be allowed if possible. Including ios::in in the modes of an ofstream object is legal, implying that the original file (if it exists) should not be truncated. iostream Package 4-35 ios class out Opens the file for output. Constructions and open operations of ofstream objects imply ios::out. For fstream objects, ios::out indicates that output operations are allowed. trunc Truncates (discards) the contents of the file (if it exists). ios::trunc is implied if ios::out is specified (including implicit specification for ofstream objects), and neither ios::app nor ios::ate is specified. nocreate Causes an open() operation to fail if the file does not exist. noreplace Causes an open() operation to fail if the file exists. 4-36 iostream Package ios class seek_dir Represents a collection of bits for positioning get and put pointers. Use this data type with functions of the filebuf, istream, ostream, and streambuf classes. The values are as follows: beg Indicates the beginning of the stream cur Indicates the current position end Indicates the end of the stream (end-of-file) Data Members const long adjustfield Collectively specifies the flags (bits) that control padding (left, right, and internal). const long basefield Collectively specifies the flags that control base conversion (dec, hex, and oct). const long floatfield Collectively specifies the flags that control floating- point value conversion (fixed and scientific). ________________________Note ________________________ When you set a flag that is part of adjustfield, basefield, or floatfield, you must ensure that the other flags within the collection are cleared. Only one flag within the collection should be set at any one time. Be aware that the setiosflags(flag) manipulator and the setf(flag) member function set only the flag or flags that you specify. If the flag you specify is part of a collection, these do not clear the other flags in the collection. The setf(flag, field) member function is useful for setting fields within a collection. Also, the hex, oct, and dec manipulators do ensure that the other flags within the basefield collection are cleared. _____________________________________________________ iostream Package 4-37 ios class Constructors and Destructors ios() Constructs an ios object with the effect undefined. It lets derived classes inherit the ios class as a virtual base class. The object is initialized with the following default values: __________________________________________________________ Element____Default_Value__________________________________ fill() The space character flags() ios::dec | ios::skipws precision()6 rdstate() ios::goodbit width()____0______________________________________________ ios(streambuf *b) Constructs an ios object, associating the constructed ios object with the streambuf object pointed to by b. The object is initialized with the same default values as the ios() constructor. virtual ~ios() Deletes an ios object. Overloaded Operators When defined, the following operators allow convenient checking of the error state of an ios. int operator !() Returns nonzero if failbit or badbit is set in the error state, which allows the use of such expressions as if (!cin) . . . . int operator void *() Converts an ios object to a pointer so that it can be compared to 0. The conversion returns a nonzero value (not meant for further use) if neither failbit nor badbit is set in the error state. This allows the use of such expressions as if (cin) . . . and if (cin >> x) . . . . 4-38 iostream Package ios class Other Member Functions int bad() const Returns a nonzero value if badbit is set in the error state; otherwise, it returns 0. This usually indicates that some operation on rdbuf() has failed, and that continued operations on the associated streambuf object may not be possible. long bitalloc() Returns a long integer with a single, previously unallocated bit set. This gives you an additional flag should you need one (to pass to ios::set(), for example). void clear(int state) Stores an integer value as the error state. A 0 value clears all bits. int eof() const Returns a nonzero value if eofbit is set in the error state; otherwise, it returns 0. This bit is usually set during an extraction and when an end-of-file has been encountered. int fail() const Returns a nonzero value if either badbit or failbit is set in the error state; otherwise, it returns 0. This usually indicates that some extraction or conversion operation has failed, but that the stream remains usable; once failbit clears, operations on the stream can usually continue. char fill() const Returns the variable currently used as the fill (padding) character. char fill(char c) Sets c as the fill (padding) character if one is needed (see width ()) and returns the previous value. The default fill character is a space. The right, left, and internal flags determine positioning of the fill character. A parameterized manipulator, setfill, is also available for setting the fill character. iostream Package 4-39 ios class long flags() const Returns the current format flags. long flags(long f) Resets all the format flags to those specified in f and returns the previous settings. The flags are as follows: skipws For scalar operations, instructs the arith- metical extractor to skip white space before beginning conversion. As a precaution against looping, arithmetical extractors signal an error if the next character is white space and the skip variable is not set. left Control padding of values. The left flag right adds a fill character after a value, right internal adds a fill character before a value, and internal adds a fill character after any leading sign or base indication, but before the value. Right-adjustment is the default if none of these flags are set. The fields are collectively identified by the static member ios::adjustfield. The fill character is controlled by the fill() function and the width after the padding is controlled by the width() function. dec Control the conversion base of a value. oct Insertions are in decimal if none of these hex flags are set. Extractions follow C++ lexical conventions for integral constants. The flags are collectively identified by the static member ios::basefield. The manipulators hex, dec, and oct are also available for setting the conversion base. showbase Converts insertions to an external form that can be read according to the C++ lexical conventions for integral constants. By default, showbase is not set. showpos Inserts a plus sign (+) into a decimal conversion of a positive integral value. 4-40 iostream Package ios class uppercase Uses an uppercase X for hexadecimal conversion when showbase is set, or uses uppercase E to print floating-point numbers in scientific notation. By default, uppercase is not set. showpoint Specifies that trailing zeros and decimal points appear in the result of a floating-point conversion. scientific Control the format to which a floating-point value is converted for insertion into a stream. fixed These two flags are collectively identified by the static member ios::floatfield. The scientific flag converts the value using scientific notation, with one digit before the decimal point. Depending on the uppercase flag, an E or an e introduces the exponent. The fixed flag converts the value to decimal notation. For both flags, the precision function determines the number of digits following the decimal point (6 is the default). If neither flag is set, then scientific notation is used only if the exponent from the conversion is less than -4 or greater than the precision. If showpoint is not set, trailing zeros are removed from the result and a decimal point appears only if followed by a digit. unitbuf Causes ostream::osfx() to perform a flush af- ter each insertion. Unit buffering constitutes a performance compromise between buffered and unbuffered output. stdio Causes ostream::osfx() to flush stdout and stderr after each insertion. int good() const Returns a nonzero value if the error state has no bits set; otherwise, it returns 0. void init(streambuf *b) Initializes the ios object; intended for use by classes derived from ios. iostream Package 4-41 ios class long& iword(int i) Returns a reference to the ith user-defined word, where i is an index into an array of words allocated by ios::xalloc. [1] int precision() const Returns the precision format state variable. int precision(int i) Sets the precision format state variable to i and returns the previous value. The variable controls the number of significant digits inserted by the floating-point inserter. The default is 6. A parameterized manipulator, setprecision, is also available for setting the precision. void *&ios::pword(int i) Returns a reference to the ith user-defined word, where i is an index into an array of words allocated by ios::xalloc. This function differs from iword() only in type. streambuf *ios::rdbuf() Returns a pointer to the streambuf object that was associated with an ios object when the ios object was constructed. int rdstate() const Returns the current error state. long setf(long setbits) Makes available to the streambuf object associated with an ios object the format flags marked in setbits and returns the previous settings. A parameterized manipulator, setiosflags, performs the same function. If you are setting a flag that is part of a collection (for example, basefield), note that this manipulator does not clear the other flags in the collection. ___________________ [1]This function references a single array that is shared among all instances of ios objects. This differs from the Digital UNIX operating system, where this function references the array that is specific to the ios instance. 4-42 iostream Package ios class long setf(long setbits, long field) Clears, in the streambuf object associated with an ios object, the format flags specified by field, then resets these flags to the settings marked in setbits. It returns the previous settings. Specifying 0 in setbits clears all the bits specified in field, as does the parameterized manipulator, resetioflags. void setstate(int state) Changes only the bits specified in the state argument. void sync_with_stdio() Solves problems that arise with mixing stdio and iostream objects. When first called, the sync_with_stdio() function resets the standard iostream functions (cin, cout, cerr, and clog) to be streams using stdiobuf objects. Subsequently, input and output using these streams may be mixed with input and output using the corresponding FILE parameters (stdin, stdout, and stderr), and properly synchronized. The sync_with_stdio() function makes cout and cerr unit buffered (see ios::unitbuf and ios::stdio). Invoking sync_with_stdio() degrades performance variably; the shorter the strings being inserted, the greater the degradation. ostream *ios::tie() const Returns the tie variable (see the following member function description). ostream *ios::tie(ostream *osp) Sets the tie variable to osp and returns its previous value. The tie variable supports automatic flushing of ios objects. The ios object that the tie variable points at is flushed if the variable is not null, and an ios object either needs more characters or has characters to be consumed. By default, cin is initially tied to cout so that attempts to get more characters from standard input result in flushing standard output. Additionally, cerr and clog are tied to cout by default. By default, the tie variable is set to 0 for other ios objects. iostream Package 4-43 ios class long unsetf(long setbits) Unsets, in the streambuf object associated with an ios object, the bits set in setbits; it returns the previous settings. int width() const Returns the field-width format variable (see the following member function description). The field width setting within the ios class is ignored during single character output: operator<<(char) and operator<<(unsigned char). int width(int n) Sets the field-width format variable to n and returns the previous value. The field width specifies a minimum number of characters for inserters. When the variable is 0 (the default), inserters insert only as many characters as needed to represent the value being inserted. When the variable is nonzero, and the value being inserted needs fewer than field-width characters to be represented, inserters insert at least that many characters using the fill character to pad the value. Numeric inserters do not truncate values even if the value being inserted is more than field-width characters. After each insertion or extraction, the field-width format variable resets to 0. A parameterized manipulator, setw, is also available for setting the field width. int xalloc() Returns a previously unused index into an array of words available for use by derived classes as format state variables. [1] ___________________ [1]This function references a single array that is shared among all instances of ios objects. This differs from the Digital UNIX operating system, where this function references the array that is specific to the ios instance. 4-44 iostream Package ios class Examples 1. cout.width(6); cout << x << " " << y; Outputs x in at least six characters, but uses only as many characters as needed for the separating space and y. In the following examples, mystrm is an ios object. 2. mystrm.clear(ios::badbit|s.rdstate()) Sets the badbit member of the io_state enumerated data type without clearing previously set bits. 3. mystrm.setf(ios::hex,ios::basefield) Changes the conversion base in mystrm to be hexadeci- mal. iostream Package 4-45 iostream class ________________________________________________________________ iostream class Provides the means to both insert into and extract from a single sequence of characters. Header File #include Alternative Header #include Declaration class iostream: public istream, public ostream { public: iostream(streambuf *); virtual ~iostream(); protected: iostream(); }; Description This class combines the istream and ostream classes. You use it to carry out bidirectional operations (inserting into and extracting from a single sequence of characters). Constructors and Destructors iostream() Constructs an iostream object, in undefined form, to enable inheritance by derived classes. iostream(streambuf *b) Constructs an iostream object. It initializes ios state variables and associates the iostream object with the streambuf object pointed to by b. 4-46 iostream Package iostream class virtual ~iostream() Deletes an iostream object. iostream Package 4-47 iostream_withassign class ________________________________________________________________ iostream_withassign class Adds an assignment operator and a constructor with no operands to the iostream class. Header File #include Alternative Header #include Declaration class iostream_withassign: public iostream { public: iostream_withassign(); virtual ~iostream_withassign(); iostream_withassign &operator=(iostream &); iostream_withassign &operator=(streambuf *); }; Description This class adds an assignment operator and a constructor with no operands to the iostream class. Constructors and Destructors iostream_withassign() Constructs an iostream_withassign object; it does no initialization. virtual ~iostream_withassign() Deletes an iostream_withassign object; no user action is required. 4-48 iostream Package iostream_withassign class Overloaded Operators iostream_withassign &operator = (iostream &) Associates iostream->rdbuf() with an iostream_withassign object and initializes the entire state of that object. iostream_withassign &operator = (streambuf *) Associates streambuf* with an iostream_withassign object and initializes the entire state of that object. iostream Package 4-49 istream class ________________________________________________________________ istream class Supports interpretation of characters extracted from an associated streambuf object. Header File #include Alternative Header #include Declaration class istream : virtual public ios { public: istream(streambuf *); virtual ~istream(); inline int gcount(); istream &get(char *ptr, int len, char delim = '\n'); istream &get(unsigned char *ptr, int len, char delim = '\n'); istream &get(char &); inline istream &get(unsigned char &); istream &get(streambuf &sb, char delim = '\n'); int get(); istream &getline(char *ptr, int len, char delim = '\n'); istream &getline(unsigned char *ptr, int len, char delim = '\n'); istream &ignore(int len = 1, int delim = ); int ipfx(int need = 0); void isfx(); int peek(); istream &putback(char); istream &read(char *s, int n); inline istream &read(unsigned char *s, int n); 4-50 iostream Package istream class istream &seekg(streampos); istream &seekg(streamoff, seek_dir); void skipwhite(); int sync(); streampos tellg(); istream &operator>>(char *); istream &operator>>(char &); istream &operator>>(short &); istream &operator>>(int &); istream &operator>>(long &); istream &operator>>(float &); istream &operator>>(double &); istream &operator>>(unsigned char *); istream &operator>>(unsigned char &); istream &operator>>(unsigned short &); istream &operator>>(unsigned int &); istream &operator>>(unsigned long &); istream &operator>>(streambuf *); inline istream &operator>>(istream &(*f)(istream &)); istream &operator>>(ios &(*f)(ios &)); protected: istream(); }; Description This class provides facilities for formatted and unformatted extraction from streambuf objects. Constructors and Destructors istream(streambuf *sb) Constructs an istream object. It initializes ios state variables and associates the istream object with the buffer pointed to by sb. virtual ~istream() Deletes an istream object. iostream Package 4-51 istream class Overloaded Operators The following operators are all formatted input extrac- tors. Given the expression ins >> x, these operators extract characters from ins and convert them to the variable x. The argument to the operator determines the type of x. Extractions are performed only if a call to ipfx(0) returns a nonzero value. Errors are indicated by setting the error state of ins. ios::failbit means that characters in ins did not represent the required type. ios::badbit means that attempts to extract characters failed. ins is always returned. The details of conversion depend on the values of the ins object format state flags and variables, and the type of x. Extractions that use width reset it to 0; otherwise, the extraction operators do not change the value of the istream object format state. istream &operator >> (char &x) istream &operator >> (unsigned char &x) Extracts a character and stores it in x. istream &operator >> (char *x) istream &operator >> (unsigned char *x) Extracts characters and stores them in the array pointed at by x, until a white-space character is found in the iostream object. The action leaves the terminating white- space character in the iostream object. If the iostream object's width() is nonzero, it is taken to be the size of the array and no more than width()-1 characters are extracted. A terminating null character ('\0') is always stored, even if nothing else is done because of the iostream object's error state. The iostream object's width() is reset to 0. istream &operator >> (short &x) istream &operator >> (int &x) istream &operator >> (long &x) istream &operator >> (unsigned short &x) istream &operator >> (unsigned int &x) 4-52 iostream Package istream class istream &operator >> (unsigned long &x) Extracts characters and converts them to an integral value according to the conversion specified in the iostream object's format flags. Converted values are stored in x. The first character can be a sign (- or +). After that, the conversion is octal if ios::oct is set in the iostream object's flags, decimal if ios::dec is set, or hexadecimal if ios::hex is set. The first nondigit that is left in the iostream object terminates the conversion. If no conversion base flag is set, the conversion proceeds according to C++ lexical conventions: if the first characters (after the optional sign) are 0x or 0X, the conversion is hexadecimal; if the first character is 0, the conversion is octal; otherwise, the conversion is decimal. If no digits are available (not counting the 0 in 0x or 0X during hex conversion), ios::failbit is set. istream &operator >> (float &x) istream &operator >> (double &x) Extracts characters and converts them according to C++ syntax for a float value or a double value. Converted values are stored in x. If no digits are available in the iostream object, or if the iostream object does not begin with a well formed floating-point or double number, ios::failbit is set. istream &operator >> (streambuf *b) Keeps getting characters from ios and inserting them into the buffer b until EOF is reached, if ios::ipfx(0) returns nonzero. Always returns the iostream object. istream &operator >> (ios &(*f)(ios &)) Calls an ios object manipulator function f for an istream object. istream &operator >> (istream &(*f)(istream &))