[ First ]  [ Previous ]  [ Next ]  [ Last ]  [ Manuals ]

 

Chapter 15.

 

27.4 Iostreams Base Classes



The include header <ios> contains the basic class definitions, types, and enumerations necessary for input and output stream reading writing and other manipulations.


Overview of Input and Output Stream Base Classes

The sections in this chapter are:


Header <ios>

The header file <ios> provides for implementation of stream objects for standard input and output.

<ios> Globals:


typedef long streamoff; 
typedef long streamsize;
class ios_base;
template <class charT, class traits = ios_traits<charT> >
class basic_ios

typedef basic_ios<char> ios;
typedef basic_ios<wchar_t> wios;

ios_base& boolalpha (ios_base& str)
ios_base& noboolalpha (ios_base& str)
 
ios_base& showbase (ios_base& str)
ios_base& noshowbase (ios_base& str)
 
ios_base& showpoint (ios_base& str)
ios_base& noshowpoint (ios_base& str)
 
ios_base& showpos (ios_base& str)
ios_base& noshowpos (ios_base& str)
 
ios_base& skipws (ios_base& str)
ios_base& noskipws (ios_base& str)
 
ios_base& uppercase (ios_base& str)
ios_base& nouppercase (ios_base& str)
 
ios_base& internal (ios_base& str)
ios_base& left (ios_base& str)
ios_base& right (ios_base& str)
 
ios_base& dec (ios_base& str)
ios_base& hex (ios_base& str)
ios_base& oct (ios_base& str)
 
ios_base& fixed (ios_base& str)
ios_base& scientific (ios_base& str)

ios_base& unitbuf(ios_base& str);
ios_base& nounitbuf(ios_base& str);

Template class fpos:
template <class stateT>
class fpos
{
public:
	fpos(streamoff o);
	operator streamoff() const;
	fpos& operator += (streamoff o);
	fpos& operator -= (streamoff o);
	fpos operator + (streamoff o) const;
	fpos operator - (streamoff o) const;
	// _lib.fpos.members_ Members
	stateT state() const;
	void state(stateT s);
};
  
template <class stateT> streamoff operator - (const fpos<stateT>& lhs, const fpos<stateT>& rhs);


Template Class fpos

The template class fpos<stateT> is a class used for specifying file position information. The template parameter corresponds to the type needed to hold state information in a multi-byte sequence (typically mbstate_t from <cwchar>). fpos is essentially a wrapper for whatever mechanisms are necessary to hold a stream position (and multi-byte state). In fact the standard stream position typedefs are defined in terms of fpos:


  typedef fpos<mbstate_t> streampos;   typedef fpos<mbstate_t> wstreampos;

The template class fpos is typically used in the istream and ostream classes in calls involving file position such as tellg, tellp, seekg and seekp. Though in these classes the fpos is typedef'd to pos_type, and can be changed to a custom implementation by specifying a traits class in the stream's template parameters.


27.4.1 Typedef Declarations

The following typedef's are defined in the class ios_base.

  typedef long streamoff;
  typedef long streamsize;

27.4.2 Class ios_base

A base class for input and output stream mechanisms

The prototype is listed below. Additional topics in this section are:

The ios_base class is a base class and includes many enumerations and mechanisms necessary for input and output operations.


27.4.3.1 Typedef Declarations

No types are specified in the current standards.


27.4.3.1.1 failure

Define a base class for types of object thrown as exceptions.

Prototype:

namespace std {


	class ios_base::failure : public exception {


		public:


		explicit failure(const string&)


		virtual ~failure();


		virtual const char* what() const;


	};


}

27.4.3.1.1.1 failure

Construct a class failure.

Prototype:

explicit failure(const string& msg);
Remarks:

The function failure() construct a class failure initializing with exception(msg).


failure::what

To return the exception message.

Prototype:

const char *what() const;
Remarks:

The function what() is use to deliver the msg.str().

Return:

Returns the message with which the exception was created.


27.4.3.1.2 Type fmtflags

An enumeration used to set various formatting flags for reading and writing of streams.

Format Flags Enumerations:

 

Flag
Effects when set
boolalpha  
insert and extract bool type in alphabetic form  
dec  
decimal output  
fixed  
when set show floating point numbers in normal manner by default that is six decimal places  
hex  
hexadecimal output  
oct  
octal output  
left  
left justified  
right  
right justified  
internal  
pad a field between signs or base characters  
scientific  
show scientific notation for floating point numbers  
showbase  
show the bases numeric values  
showpoint  
show the decimal point and trailing zeros  
showpos  
show the leading plus sign for positive numbers  
skipws  
skip leading white spaces with input  
unitbuf  
buffer the output and flush after insertion operation  
uppercase  
show the scientific notation, x or o in uppercase  

Format flag field constants:

 

Constants
Allowable values
adjustfield  
left | right | internal  
basefield  
dec | oct | hex  
floatfield  
scientific | fixed  

Example of ios format flags usage:


see basic_ios::setf() and basic_ios::unsetf()


27.4.3.1.3 Type iostate

An enumeration that is used to define the various states of a stream.

Enumeration iostate:

 

Flags
Usage
goodbit  
True when all of badbit, eofbit and failbit are false.  
badbit  
True when the stream is in an irrecoverable error state (such as failure due to lack of memory)  
failbit  
rue when a read or a write has failed for any reason (This can happen for example when the input read a character while attempting to read an integer.)  
eofbit  
True when the end of the stream has been detected. Note that eofbit can be set during a read, and yet the read may still succeed (failbit not set). (This can happen for example when an integer is the last character in a file.)     note: see variance from AT&T standard  

Example of ios iostate flags usage::


See basic_ios::setstate() and basic_ios::rdstate()


27.4.3.1.4 Type openmode

An enumeration that is used to specify various file opening modes.

Enumeration openmode:

 

Mode
Definition
app  
Start the read or write at end of the file  
ate  
Start the read or write immediately at the end  
binary  
binary file  
in  
Start the read at end of the stream  
out  
Start the write at the beginning of the stream  
trunc  
Start the read or write at the beginning of the stream  


27.4.3.1.5 Type seekdir

An enumeration to position a pointer to a specific place in a file stream.

Enumeration seekdir:

 

Enumeration
Position
beg  
Begging of stream  
cur  
Current position of stream  
end  
End of stream  

Example of ios seekdir usage::


See: streambuf::pubseekoff


27.4.3.1.6 Class Init

An object that associates <iostream> object buffers with standard stream declared in <cstdio>.

Prototype:

namespace std {


class ios_base::Init {


	public:


	Init();


	~Init();


	private:


	// static int 


	};


}

Class Init Constructor


Default Constructor

To construct an object of class Init;

Prototype:

Init();
Remarks:

The constructor Init() constructs an object of class Init. If init_cnt is zero the function stores the value one and constructs cin, cout, cerr, clog, win, wout, werr and wlog. In any case the constructor then adds one to init_cnt.


Destructor

Prototype:

~Init();
Remarks:

The destructor subtracts one from init_cnt and if the result is one calls cout.flush(), cerr.flush() and clog.flush().


27.4.3.2 ios_base fmtflags state functions

To set the state of the ios_base format flags.


flags

To alter formatting flags using a mask.

Prototype:

fmtflags flags() const


fmtflags flags(fmtflags)
Remarks:

Use flags() when you would like to use a mask of several flags, or would like to save the current format configuration. The return value of flags() returns the current fmtflags. The overloaded flags(fmtflags) alters the format flags but will return the value prior to the flags being changed.

Return:

The fmtflags type before alterations.


NOTE

See ios enumerators for a list of fmtflags.


See Also::

setiosflags() and resetiosflags()

Example of flags() usage::


#include <iostream>
	// showf() displays flag settings
void showf();

int main()
{
using namespace std;
	showf(); // show format flags

	cout << "press enter to continue" << endl;
	cin.get();

	cout.setf(ios::right|ios::showpoint|ios::fixed);
	showf();
	return 0;
}

// showf() displays flag settings
void showf()
{
using namespace std;

	char fflags[][12] = {
          "boolalpha",
          "dec",
          "fixed",
          "hex",
          "internal",
          "left",
          "oct",
          "right",
          "scientific",
          "showbase",
          "showpoint",
          "showpos",
          "skipws",
          "unitbuf",
          "uppercase"
	};
	
	long f = cout.flags();   // get flag settings
	cout.width(9); // for demonstration 
		// check each flag
	for(long i=1, j =0; i<=0x4000; i = i<<1, j++)
	{
		cout.width(10); // for demonstration
		if(i & f) 
			cout << fflags[j] << " is on \n";
		else 
			cout << fflags[j] << " is off \n";
	}

	cout << "\n";
}





Result:
boolalpha  is off 
dec        is on 
fixed      is off 
hex        is off 
internal   is off 
left       is off 
oct        is off 
right      is off 
scientific is off 
showbase   is off 
showpoint  is off 
showpos    is off 
skipws     is on 
unitbuf    is off 
uppercase  is off 
press enter to continue

 boolalpha is off 
       dec is on 
     fixed is on 
       hex is off 
  internal is off 
      left is off 
       oct is off 
     right is on 
scientific is off 
  showbase is off 
 showpoint is on 
   showpos is off 
    skipws is on 
   unitbuf is off 
uppercase is off 

 



setf

 

Set the stream format flags.

Prototype:

fmtflags setf(fmtflags)

 

fmtflags setf(fmtflags, fmtflags)

Remarks:

You should use the function setf() to set the formatting flags for input/output. It is overloaded.

The single argument form of setf() sets the flags in the mask. The two argument form of setf() clears the flags in the first argument before setting the flags

with the second argument.

Return:

type basic_ios::fmtflags

Example of setf() usage::


#include <iostream>
int main()
{
using namespace std;

	double d = 10.01;

	cout.setf(ios::showpos | ios::showpoint);
	cout << d << endl;                       
	cout.setf(ios::showpoint, ios::showpos | ios::showpoint);
	cout << d << endl;    

	return 0;
}





Result:
+10.01
10.01

 



unsetf

 

To un-set previously set formatting flags.

Prototype:

void unsetf(fmtflags)

Remarks:

Use the unsetf() function to reset any format flags to a previous condition.

You would normally store the return value of setf() in order to achieve this task.

Return:

There is no return.

Example of unsetf() usage::


#include <iostream>
int main()
{
using namespace std;

	double d = 10.01;

	cout.setf(ios::showpos | ios::showpoint);
	cout << d << endl;

	cout.unsetf(ios::showpoint);
	cout << d << endl;
	return 0;
}





Result:
+10.01
+10.01

 



precision

 

Set and return the current format precision.

Prototype:

streamsize precision() const 

 

streamsize precision(streamsize prec) 

Remarks:

Use the precision() function with floating point numbers to limit the number of

digits in the output. You may use precision() with scientific or non-scientific floating point numbers. You

may use the overloaded precision() to retrieve the current precision that is set.

 

With the flag ios::floatfield set the number in precision refers to the total number of significant digits generated. If

the settings are for either ios::scientific or ios::fixed then the precision refers to the number of digits after the decimal

place.


NOTE

This means that ios::scientific will have one more significant digit than ios::floatfield, and ios::fixed will have a varying number of digits.


Return:

The current value set.

See Also:

setprecision()

Example of precision() usage::


#include <iostream>
#include <cmath>
const double pi = 4 * std::atan(1.0);

int main()
{
using namespace std;

	double TenPi = 10*pi;
	
	cout.precision(5);
	cout.unsetf(ios::floatfield);
	cout << "floatfield:\t" << TenPi << endl;
	cout.setf(ios::scientific, ios::floatfield);
	cout << "scientific:\t" << TenPi << endl;	
	cout.setf(ios::fixed, ios::floatfield);
	cout << "fixed:\t\t" << TenPi << endl;
	return 0;
}





Result:
floatfield: 31.416
scientific: 3.14159e+01
fixed:      31.41593

 



width

 

To set the width of the output field.

Prototype:

streamsize width() const 

 

streamsize width(streamsize wide)

Remarks:

Use the width() function to set the field size for output. The function is

overloaded to return just the current width setting if there is

no parameter or to store and then return the previous setting

before changing the fields width to the new parameter.


NOTE

Width is the one and only modifier that is not sticky and needs to be

reset with each use. Width is reset to width(0) after each use.


Return:

The previous width setting is returned.

Example of width() usage: :


#include <iostream> 
int main()
{
using namespace std;

	int width;

	cout.width(8); 
	width = cout.width();
	cout.fill('*'); 
	cout << "Hi!" << '\n';

	// reset to left justified blank filler
	cout<< "Hi!" << '\n'; 

	cout.width(width);
	cout<< "Hi!" << endl;

	return 0; 
}





Result:
Hi!*****
Hi!
Hi!***** 

 



27.4.3.3 ios_base locale functions

 

Sets the locale for input output operations.


imbue

 

Stores a value representing the locale.

Prototype:

locale imbue(const locale loc);

Remarks:

The precondition of the argument loc is equal to getloc().

Return:

The previous value of getloc().


getloc

 

Determined the imbued locale for input output operations.

Prototype:

locale getloc() const;

Return:

The global C++ locale if no locale has been imbued. Otherwise

it returns the locale of the input and output operations.


27.4.3.4 ios_base storage function

 

To allocate storage pointers.


xalloc

 

Allocation function.

Prototype:

static int xalloc()

Return:

index++.


iword

 

Allocate an array of int and store a pointer.

Remark:

If iarray is a null pointer allocate an array and store a pointer to the

first element. The function extends the array as necessary to

include iarray[idx]. Each new allocated element is initialized to the return value

may be invalid.


NOTE

After a subsequent call to iword() for the same object the return

value may be invalid.


Return:

irray[idx]


pword

 

Allocate an array of pointers.

Prototype:

void * &pword(int idx)

Remarks:

If parray is a null pointer allocates an array of void pointers.

Then extends parray as necessary to include the element parray[idx].


NOTE

After a subsequent call to pword() for the same object the return

value may be invalid.


Return:

parray[idx].


register_callback

 

Registers functions when an event occurs.

Prototype:

void register_callback

 

	(event_callback fn,

 

	int index);

Remarks:

Registers the pair (fn, index) such that during calls to -imbue(), copyfmt() or ~ios_base() the function fn is called with argument index. Function registered are called when an event occurs, in opposite

order of registration. Functions registered while a callback function

is active are not called until the next event.


NOTE

Identical pairs are not merged and a function registered twice

will be called twice.



sync_with_stdio

 

Synchronizes stream input output with 'C' input and output functions.

Prototype:

static bool sync_with_stdio(bool sync = true);

Remarks:

Is not supported in the Metrowerks Standard Library.

Return:

Always returns true indicating that the MSLstreams are always synchronized with the

C streams.


27.4.3.5 ios_base Constructor


Default Constructor

 

Construct and destruct an object of class ios_base

Prototype:

protected:

 

	ios_base();

Remarks:

The ios_base constructor is protected so it may only be derived from. It the

values of the ios_base members are undermined.


Destructor

Prototype:

~ios_base();

Remarks:

Calls registered callbacks and destroys an object of class ios_base.


27.4.4 Template class basic_ios

 

A template class for input and output streams.

 

The prototype is listed below. Additional topics in this section

are:

 

  • "27.4.4.1 basic_ios Constructor"
  • "27.4.4.2 Member Functions"
  • "27.4.4.3 basic_ios iostate flags functions"Prototype:
    namespace std{

     

    template<class charT, 

     

    		class traits = ios_traits<charT> >

     

    class basic_ios : public ios_base {

     

    	public:

     

    	typedef charT char_type;

     

    	typedef typename traits::int_type int_type;

     

    	typedef typename traits::pos_type pos_type;

     

    	typedef typename traits::off_type off_type;

     

    
    			
    			
    			

     

    	operator bool() const;

     

    	bool operator!() const;

     

    	iostate rdstate() const;

     

    	void clear(iostate state = goodbit);

     

    	void setstate(iostate state);

     

    	bool good() const;

     

    	bool eof() const;

     

    	bool fail() const;

     

    	bool bad() const;

     

    
    			
    			
    			

     

    	explicit basic_ios

     

    		(basic_streambuf<charT, traits>, 

     

    		traits *sb);

     

    
    			
    			
    			

     

    	virtual ~basic_ios();

     

    
    			
    			
    			

     

    	basic_ostream<charT, traits>* tie() const;

     

    	basic_ostream<charT, traits>* 

     

    		tie(basic_streambuf<charT, traits* sb);

     

    
    			
    			
    			

     

    	basic_streambuf(charT, traits>* rdbuf() 
    const;

     

    	basic_streambuf(charT, traits>* 

     

    		rdbuf(basic_streambuf<charT, traits>* sb);

     

    
    			
    			
    			

     

    	basic_ios& copyfmt(const basic_ios& rhs);

     

    
    			
    			
    			

     

    	char_type fill()const;

     

    	char_type fill(char_type ch);

     

    
    			
    			
    			

     

    	locale imbue(const locale& loc);

     

    
    			
    			
    			

     

    	protected:

     

    	basic_ios();

     

    	void init(basic_streambuf<charT, traits>* 
    sb);

     

    	};

     

    }

    Remarks:

The basic_ios template class is a base class and includes many enumerations and mechanisms

necessary for input and output operations.


27.4.4.1 basic_ios Constructor


Default and Overloaded Constructor

 

Construct an object of class basic_ios and assign values.

Prototype:

public:

 

	explicit basic_ios

 

	(basic_streambuf<charT,traits>* sb);

 

protected:

 

	basic_ios();

Remarks:

The basic_ios constructor creates and object to class basic_ios and assigns values to its member functions by calling init().


Destructor

Prototype:

virtual ~basic_ios();

Remarks:

Destroys an object of type basic_ios.

Remarks:

The conditions of the member functions after init() are shown

in the following table.

Conditions after init():

 

Member
Postcondition Value
rdbuf()  

sb  

tie()  

zero  

rdstate()  

goodbit if stream buffer is not a null pointer otherwise badbit.  

exceptions()  

goodbit  

flags()  

skipws | dec  

width()  

zero  

precision()  

six  

fill()  

the space character  

getloc()  

locale::classic()  

iarray  

a null pointer  

parray  

a null pointer  

 

 


27.4.4.2 Member Functions


tie

 

To tie an ostream to the calling stream.

Prototype:

basic_ostream<charT, traits>* tie() const;

 

basic_ostream<charT, traits>* tie

 

	(basic_ostream<charT, traits>* tiestr);

Remarks:

Any stream can have an ostream tied to it to ensure that the ostream is flushed before any operation. The standard input and output

objects cin and cout are tied to ensure that cout is flushed before any cin operation. The function tie() is overloaded the parameterless version returns the current

ostream that is tied if any. The tie() function with an argument ties the new object to the ostream

and returns a pointer if any from the first. The postcondition

of tie() function that takes the argument tiestr is that tiestr is equal to tie();

Return:

A pointer to type ostream that is or previously was tied, or zero if there was none.

Example of tie() usage::


The file MW Reference contains
Metrowerks CodeWarrior "Software at Work"





#include <iostream>
#include <fstream>
#include <cstdlib>
char inFile[] = "MW Reference";
 
int main()
{
using namespace std;

	ifstream inOut(inFile, ios::in | ios::out);
	if(!inOut.is_open()) 
		{ cout << "file is not open"; exit(1);}
	ostream Out(inOut.rdbuf());

	if(inOut.tie()) 
		cout << "The streams are tied\n";
	else cout << "The streams are not tied\n";

	inOut.tie(&Out);
	inOut.rdbuf()->pubseekoff(0, ios::end);

	char str[] = "\nRegistered Trademark";
	Out << str;
	
	if(inOut.tie()) 
		cout << "The streams are tied\n";
	else cout << "The streams are not tied\n";

	inOut.close();
	return 0;
}





Result:
The streams are not tied
The streams are tied
The file MW Reference now contains
Metrowerks CodeWarrior "Software at Work"
Registered Trademark

 



rdbuf

 

To retrieve a pointer to the stream buffer.

Prototype:

basic_streambuf<charT, traits>* rdbuf() const;

 

basic_streambuf<charT, traits>* rdbuf

 

	(basic_streambuf<charT, traits>* sb);

Remarks:

To manipulate a stream for random access or synchronization it

is necessary to retrieve a pointer to the streams buffer. The

function rdbuf() allows you to retrieve this pointer. The rdbuf() function that takes an argument has the postcondition of sb is equal to rdbuf().

Return:

A pointer to basic_streambuf object.

Example of rdbuf() usage::


#include <iostream>
struct address {
	int number;
	char street[40];
} addbook;

int main()
{
using namespace std;

	cout << "Enter your street number: ";
	cin >> addbook.number;

	cin.rdbuf()->pubsync(); // buffer flush

	cout << "Enter your street name: "; 
	cin.get(addbook.street, 40);

	cout << "Your address is: "
			<< addbook.number << " " << addbook.street;

	return 0;
}





Result:
Enter your street number: 2201
Enter your street name: Donley Drive
Your address is: 2201 Donley Drive

 



imbue

 

Stores a value representing the locale.

Prototype:

locale imbue(const locale& rhs);

Remarks:

The function imbue() calls ios_base::imbue() and
rdbuf->pubimbue().

Return:

The current locale.


fill

 

To insert characters into the stream's unused spaces.

Prototype:

char_type fill() const

 

char_type fill(char_type)

Remarks:

Use fill(char_type) in output to fill blank spaces with a character. The function

fill() is overloaded to return the current filler without altering it.

Return:

The current character being used as a filler.

See Also:

manipulator setfill()

Example of fill() usage::


#include <iostream> 
int main()
{
using namespace std;

	char fill;

	cout.width(8); 
	cout.fill('*'); 
	fill = cout.fill();
	cout<< "Hi!" << "\n";
	cout << "The filler is a " << fill << endl;
	
	return 0;
}





Result:
Hi!*****
The filler is a * 

 



copyfmt

 

Copies a basic_ios object.

Prototype:

basic_ios& copyfmt(const basic_ios& rhs);

Remarks:

Assigns members of *this object the corresponding objects of the rhs argument with certain exceptions. The exceptions are rdstate() is unchanged, exceptions() is altered last, and the contents or pword and iword arrays are copied not the pointers themselves.

Return:

The this pointer.


27.4.4.3 basic_ios iostate flags functions

 

To set flags pertaining to the state of the input and output

streams.


operator bool

 

A bool operator.

Prototype:

operator bool() const; 

Return:

!fail()


operator !

 

A bool not operator.

Prototype:

bool operator ! ();

Return:

fail().


rdstate

 

To retrieve the state of the current formatting flags.

Prototype:

iostate rdstate() const

Remarks:

This member function allows you to read and check the current

status of the input and output formatting flags. The returned

value may be stored for use in the function ios::setstate() to reset the flags at a later date.

Return:

Type iostate used in ios::setstate()

See Also:

ios::setstate()

Example of rdstate() usage::


The file MW Reference contains:
ABCDEFGHIJKLMNOPQRSTUVWXYZ





#include <iostream>
#include <fstream>
#include <cstdlib>
char * inFile = "MW Reference";

using namespace std;

void status(ifstream &in);

int main()
{

	ifstream in(inFile);
	if(!in.is_open()) 
	{
		cout << "could not open file for input";
		exit(1);
	}

	int count = 0;
	int c;
	while((c = in.get()) != EOF) 
	{
		// simulate a bad bit
		if(count++ == 12) in.setstate(ios::badbit);
		status(in);
	}

	status(in);
	in.close();   
	return 0;
}

void status(ifstream &in)
{
	int i = in.rdstate();
	switch (i) {
	case ios::eofbit : cout << "EOF encountered \n"; 
											break;
	case ios::failbit : cout << "Non-Fatal I/O Error n";
											break;
	case ios::goodbit : cout << "GoodBit set \n";     
											break;
	case ios::badbit : cout << "Fatal I/O Error \n"; 
											break;
	}
}





Result:
GoodBit set
GoodBit set 
GoodBit set 
GoodBit set 
GoodBit set 
GoodBit set 
GoodBit set 
GoodBit set 
GoodBit set 
GoodBit set 
GoodBit set 
GoodBit set 
Fatal I/O Error 

 



clear

 

Clears iostate field.

Prototype:

void clear

 

	(iostate state = goodbit) throw failure;

Remarks:

Use clear() to reset the failbit, eofbit or a badbit that may have been set inadvertently when you wish to override

for continuation of your processing. Postcondition of clear is

the argument is equal to rdstate().


NOTE

If rdstate() and exceptions() != 0 an exception is thrown.


Return:

No value is returned.

Example of clear() usage::


The file MW Reference contains:
ABCDEFGH





#include <iostream>
#include <fstream>
#include <cstdlib>
char * inFile = "MW Reference";

using namespace std;

void status(ifstream &in);

int main()
{
	ifstream in(inFile);
	if(!in.is_open()) 
	{
			cout << "could not open file for input";
			exit(1);
	}

int count = 0;
	int c;
	while((c = in.get()) != EOF) {
	if(count++ == 4) 
	{
		// simulate a failed state
		in.setstate(ios::failbit);
		in.clear();
	}
	status(in);
	}

	status(in);
	in.close();
	return 0;
}

void status(ifstream &in)
{
		// note: eof() is not needed in this example   
		// if(in.eof()) cout << "EOF encountered \n"
	if(in.fail()) cout << "Non-Fatal I/O Error \n";
	if(in.good()) cout << "GoodBit set \n";   
	if(in.bad()) cout << "Fatal I/O Error \n"; 
}





Result:
GoodBit set 
GoodBit set 
GoodBit set 
GoodBit set 
GoodBit set 
GoodBit set 
GoodBit set 
GoodBit set 
Non-Fatal I/O Error 

 



setstate

 

To set the state of the format flags.

Prototype:

void setstate(iostate state) throw(failure);

Remarks:

Calls clear(rdstate() | state) and may throw and exception.

Return:

No Return

Example of setstate() usage::


See ios::rdstate()

 



good

 

To test for the lack of error bits being set.

Prototype:

bool good() const;

Remarks:

Use the function good() to test for the lack of error bits being set.

 

Returns

 

True if rdstate() == 0.

Example of good() usage::


See basic_ios::bad()

 



eof

 

To test for the eofbit setting.

Prototype:

bool eof() const

Remarks:

Use the eof() function to test for an eofbit setting in a stream

being processed under some conditions. This end of file bit is

not set by stream opening or closing, but only for operations

that detects an end of file condition.

Return:

True if eofbit is set in rdstate().

Example of eof() usage::


MW Reference is simply a one line text document
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz





#include <iostream>
#include <fstream>
#include <cstdlib>
const char* TheText = "MW Reference";

int main()
{ 
using namespace std;

	ifstream in(TheText);
	if(!in.is_open()) 
	{
		cout << "Couldn't open file for input"; 
		exit(1);
	}

	int i = 0;
	char c;
	cout.setf(ios::uppercase);

		//eofbit is not set under normal file opening
	while(!in.eof()) 
	{
		c = in.get();
		cout << c << " " << hex << int(c) << "\n";

		// simulate an end of file state           
		if(++i == 5) in.setstate(ios::eofbit);
	}    
return 0;
}





Result:
A 41
B 42
C 43
D 44
E 45

 



fail

 

To test for stream reading failure from any cause.

Prototype:

bool fail() const

Remarks:

The member function fail() will test for failbit and badbit .

Return:

True if failbit or badbit is set in rdstate().

Example of fail() usage::


MW Reference file for input contains.
float 33.33 double 3.16e+10 Integer 789 character C





#include <iostream>
#include <fstream>
#include <cstdlib>
int main()
{
using namespace std;

	char inFile[] = "MW Reference";
	ifstream in(inFile);
	if(!in.is_open()) 
	{cout << "Cannot open input file"; exit(1);}

	char ch = 0;

	while(!in.fail()) 
	{
		if(ch)cout.put(ch);
		in.get(ch);
	}
	
	return 0;
}





Result:
float 33.33 double 3.16e+10 integer 789 character C

 



bad

 

To test for fatal I/O error.

Prototype:

bool bad() const

Remarks:

Use the member function bad() to test if a fatal input or output error occurred which sets

the badbit flag in the stream.

Return:

True if badbit is set in rdstate().

See Also:

basic_ios::fail()

Example of bad() usage::


The File MW Reference contains:
abcdefghijklmnopqrstuvwxyz





#include <iostream>
#include <fstream>
#include <cstdlib>
char * inFile = "MW Reference";

using namespace std;

void status(ifstream &in);

int main()
{
	ifstream in(inFile);
	if(!in.is_open()) 
	{
		cout << "could not open file for input";
		exit(1);
	}

	int count = 0;
	int c;
	while((c = in.get()) != EOF) 
	{
		// simulate a failed state
		if(count++ == 4) in.setstate(ios::failbit);
		status(in);
	}

	status(in);
	in.close();
	return 0;
}

void status(ifstream &in)
{
		// note: eof() is not needed in this example 
		// if(in.eof()) cout << "EOF encountered \n";

	if(in.fail()) cout << "Non-Fatal I/O Error \n";
	if(in.good()) cout << "GoodBit set \n";   
	if(in.bad()) cout << "Fatal I/O Error \n";
}





Result:
GoodBit set 
GoodBit set 
GoodBit set 
GoodBit set 
Non-Fatal I/O Error 
Non-Fatal I/O Error 

 



exceptions

 

To handle basic_ios exceptions.

Prototype:

iostate exceptions() const;

 

void exceptions(iostate except);

Remarks:

The function exceptions() determines what elements in rdstate() cause exceptions to be thrown. The overloaded exceptions(iostate) calls clear(rdstate()) and leaves the argument except equal to exceptions().

Return:

A mask that determines what elements set in rdstate() cause

undefined behavior.


27.4.5 ios_base manipulators

 

To provide an in line input and output formatting mechanism.

 

The topics in this section are:

 


27.4.5.1 fmtflags manipulators

 

To provide an in line input and output numerical formatting mechanism.

Prototype of ios_base manipulators:

 

Manipulator
Definition
ios_base& boolalpha(ios_base&)  

insert and extract bool type in alphabetic format  

ios_base& noboolalpha (ios_base&)  

unsets insert and extract bool type in alphabetic format  

 

 

ios_base& showbase(ios_base& b)  

set the number base to parameter b  

ios_base& noshowbase (ios_base&)  

remove show base  

 

 

ios_base& showpoint(ios_base&)  

show decimal point  

ios_base& noshowpoint(ios_base&)  

do not show decimal point  

 

 

ios_base& showpos(ios_base&)  

show the positive sign  

ios_base& noshowpos(ios_base&)  

do not show positive sign  

 

 

ios_base& skipws(ios_base&)  

input only skip white spaces  

ios_base& noskipws(ios_base&)  

input only no skip white spaces  

 

 

ios_base& uppercase(ios_base&)  

show scientific in uppercase  

ios_base& nouppercase (ios_base&)  

do not show scientific in uppercase  

 

 

ios_base& unitbuf   (ios_base::unitbuf)  

set the unitbuf flag  

ios_base& nounitbuf (ios_base::unitbuf)  

unset the unitbuf flag  

 

 

Remarks:

Manipulators are used in the stream to alter the formatting of

the stream.

Return:

A reference to an object of type ios_base is returned to the stream. (The this pointer.)


27.4.5.2 adjustfield manipulators

 

To provide an in line input and output orientation formatting

mechanism.

Adjustfield manipulators:

 

Manipulator
Definition
ios_base& internal(ios_base&)  

fill between indicator and value  

ios_base& left(ios_base&)  

left justify in a field  

ios_base& right(ios_base&)  

right justify in a field  

 

 

Remarks:

Manipulators are used in the stream to alter the formatting of

the stream.

Return:

A reference to an object of type ios_base is returned to the stream. (The this pointer.)


27.4.5.3 basefield manipulators

 

To provide an in line input and output numerical formatting mechanism.

Basefield manipulators:

 

Manipulator
Definition
ios_base& dec(ios_base&)  

format output data as a decimal  

ios_base& oct(ios_base&)  

format output data as octal  

ios_base& hex(ios_base&)  

format output data as hexadecimal  

 

 

Remarks:

Manipulators are used in the stream to alter the formatting of

the stream.

Return:

A reference to an object of type ios_base is returned to the stream. (The this pointer.)


27.4.5.4 floatfield manipulators

 

To provide an in line input and output numerical formatting mechanism.

Floatfield manipulators:

 

Manipulator
Definition
ios_base& fixed(ios_base&)  

format in fixed point notation  

ios_base& scientific(ios_base&)  

use scientific notation  

 

 

Remarks:

Manipulators are used in the stream to alter the formatting of

the stream.

Return:

A reference to an object of type ios_base is returned to the stream. (The this pointer.)

Example of manipulator usage::


#include <iostream>
#include <iomanip>
int main()
{
using namespace std;

	long number = 64; 

	cout << "Original Number is " 
			<< number << "\n\n";
	cout << showbase;
	cout << setw(30) << "Hexadecimal :" 
			<< hex << setw(10) << right 
			<< number <<'\n';
	cout << setw(30) << "Octal :" << oct 
			<< setw(10) << left 
			<< number <<'\n';
	cout << setw(30) << "Decimal :" << dec 
			<< setw(10) << right 
			<< number << endl;   

	return 0;
}





Result:
Original Number is 64
Hexadecimal :                       0x40
                       Octal :0100      
Decimal :                             64

 



Overloading Manipulators

 

To provide an in line formatting mechanism.

Prototype:

The basic template for parameterless manipulators,

 

ostream &manip-name(ostream &stream)

 

{

 

	// coding

 

	return stream;

 

} 

Remarks:

Use overloaded manipulators to provide specific and unique formatting

methods relative to one class.

Return:

A reference to ostream. (Usually the this pointer.)

See Also:

<iomanip> for manipulators with parameters

Example of overloaded manipulator usage::


#include <iostream>
using namespace std;

ostream &rJus(ostream &stream);

int main()
{
	cout << "align right " << rJus << "for column";
	return 0; 
}
 
ostream &rJus(ostream &stream)
{
	stream.width(30);
	stream.setf(ios::right);
	return stream;
}





Result:
align right                     for column

 


 

 

 

 

 


[ First ]  [ Previous ]  [ Next ]  [ Last ]  [ Manuals ]

Visit the Metrowerks website at: http://www.metrowerks.com
For assistance contact Metrowerks Technical Support at: cw_support@metrowerks.com
Copyright © 2000, Metrowerks Corp. All rights reserved.

Last updated: July 21, 2000