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

 

Chapter 17.

 

27.6 Formatting And Manipulators



This chapter discusses formatting and manipulators in the input/output library.


Overview of Formatting and Manipulators

There are three headers-<istream>, <ostream>, and <iomanip>-that contain stream formatting and manipulator routines and implementations.

The sections in this chapter are:


Headers

This section lists the header for istream, ostream, and iomanip.


Header <istream>

Prototype:


#include <ios>
namespace std{
template
	<class charT, class traits = ios_traits<charT> > 
class basic_istream;
typedef basic_istream<char> istream;
typedef basic_istream<wchar_t> wistream;

template
	<class charT, class traits>
basic_istream<charT, traits> &ws
	(basic_istream<charT,traits> (is);
}


Header <ostream>


#include <ios>
namespace std{
template
	<class charT, class traits = ios_traits<charT> >
class basic_ostream;
typedef basic_ostream<char> ostream;
typedef basic_ostream<wchar_t> wostream;

template
	<class charT, class traits>
basic_ostream<charT, traits> &endl
	(basic_ostream<charT,traits>& os);

template
	<class charT, class traits>
basic_ostream<charT, traits> &ends
	(basic_ostream<charT,traits>& os);

template
	<class charT, class traits>
basic_ostream<charT, traits> &flush
	(basic_ostream<charT,traits>& os);
}


Header <iomanip>


#include <ios>
namespace std {
// return types are unspecified
T1 resetiosflags(ios_base::fmtflags mask);
T2 setiosflags (ios_base::fmtflag mask);
T3 setbase(int base);
T4 setfill(int c);
T5 setprecision(int n);
T6 setw(int n);
}


27.6.1 Input Streams

The header <istream> controls input from a stream buffer.

The topics in this section are:


27.6.1.1 Template class basic_istream

A class that defines several functions for stream input mechanisms from a controlled stream buffer.


namespace std{
template 
	<class charT, class traits = ios_traits<charT> >
class basic_istream : virtual public basic_ios<charT, traits> {
	public:
	typedef charT
	typedef typename traits::int_type int_type;
	typedef typename traits::pos_type pos_type;
	typedef typename traits::off_type off_type;
	explicit basic_istream
	(basic_streambuf<charT, traits>* sb);

	virtual ~basic_istream();

	class sentry;

	basic_istream<charT, traits>& operator >>
		(basic_istream<charT, traits>& (*pf)
		(basic_istream<charT,traits>&))
	basic_istream<charT, traits>& operator >>
		(basic_ios<charT, traits>& (*pf)
		(basic_ios<charT,traits>&))
	basic_istream<charT, traits>& operator >>
		(char_type *s);
	basic_istream<charT, traits>& operator >>
		(char_type& c);
	basic_istream<charT, traits>& operator >>
		(bool& n);
	basic_istream<charT, traits>& operator >>
		(short& n);
	basic_istream<charT, traits>& operator >>
		(unsigned short& n);
	basic_istream<charT, traits>& operator >>
		(int& n);
	basic_istream<charT, traits>& operator >>
		(unsigned int& n);
	basic_istream<charT, traits>& operator >>
		(	long& n);
	basic_istream<charT, traits>& operator >>
		(unsigned long& n);
	basic_istream<charT, traits>& operator >>
		(float& f);
	basic_istream<charT, traits>& operator >>
		(double& f);
	basic_istream<charT, traits>& operator >>
		(long double & f);
	basic_istream<charT, traits>& operator >>
		(void*& p);
	basic_istream<charT, traits>& operator >>
		(basic_streambuf<char_type, traits>* sb);

	streamsize gcount() const;
	int_type get();
	basic_istream<charT, traits>& get
		(char_type& c);
	basic_istream<charT, traits>& get
		(char_type* s,
		streamsize n, 
		char_type delim = traits::newline());
	basic_istream<charT, traits>& get
		(basic_steambuf<char_type, 
		traits>& sb, 
		char_type delim = traits::newline());

	basic_istream<charT, traits>& getline
		(char_type* s, 
		streamsize n, 
		char_type delim = traits::newline());

	basic_istream<charT, traits>& ignore
		(steamsize n = 1, 
		int_type delim = traits::eof());

	int_type peek();

	basic_istream<charT, traits>& read	
		(char_type* s, streamsize n);
	streamsize readsome(charT_type* s, streamsize n);

	basic_istream<charT, traits>& putback(char_type c);
	basic_istream<charT, traits>&unget();

	int sync();

	pos_type tellg();
	basic_istream<charT, traits>& seekg
		(pos_type);
	basic_istream<charT, traits>& seekg
		(off_type, ios_base::seekdir);
};
}

Remarks:

The basic_istream class is derived from the basic_ios class and provides many functions for input operations.


27.6.1.1.1 basic_istream Constructors


constructor

Creates an basic_istream object.

Prototype:

explicit basic_istream


(basic_streambuf<charT, traits>* sb);
Remarks:

The basic_istream constructor is overloaded. It can be created as a base class with no arguments. It may be a simple input class initialized to a previous object's stream buffer.


Destructor

Destroy the basic_istream object.

Prototype:

virtual ~basic_istream() 
Remarks:

The basic_istream destructor removes from memory the basic_istream object.

Example of basic_istream() usage::


MW Reference file contains 
Ask the teacher anything you want to know





#include <iostream>
#include <fstream>
#include <cstdlib>
 
int main()
{
using namespace std;
 
	ofstream out("MW Reference", ios::out | ios::in); 
	if(!out.is_open()) 
		{cout << "file did not open"; exit(1);} 
	
	istream inOut(out.rdbuf());
	 
	char c;
	while(inOut.get(c)) cout.put(c);
	return 0;
}





Result:
Ask the teacher anything you want to know

 



27.6.1.1.2 Class basic_istream::sentry

 

A class for exception safe prefix and suffix operations.

Prototype:

namespace std {

 

template

 

	<class charT, 

 

	class traits = char_traits<charT> > 

 

class basic_istream<chartT, traits>::sentry {

 

	bool ok_;

 

	public:

 

	explicit sentry

 

		(basic_istream<charT, 

 

		traits>& is,

 

		bool noskipws = false);

 

	~sentry();

 

	operator bool() {return ok_;}

 

};

 

}


Class basic_istream::sentry Constructor


Constructor

 

Prepare for formatted or unformatted input

Prototype:

explicit sentry

 

	(basic_istream<charT, 

 

	traits>& is,

 

	bool noskipws = false);

Remarks:

If after the operation is.good() is true ok_ equals true otherwise ok_ equals false. The constructor may call setstate(failbit) which may throw an exception.


Destructor

Prototype:

~sentry();

Remarks:

The destructor has no effects.


sentry::Operator bool

 

To return the value of the data member ok_.

Prototype :

operator bool();

Return:

Operator bool returns the value of ok_


27.6.1.2 Formatted input functions

 

Formatted function provide mechanisms for input operations of

specific types.


27.6.1.2.1 Common requirements

 

Each formatted input function begins by calling ipfx() and if

the scan fails for any reason calls setstate(failbit). The behavior

of the scan functions are "as if" it was fscanf().


27.6.1.2.2 Arithmetic Extractors Operator >>

 

Extractors that provide formatted arithmetic input operation.

Prototype:

basic_istream<charT, traits>& operator >>

 

	(bool & n);

 

basic_istream<charT, traits>& operator >>

 

	(short &n);


Remarks:

 

Extracts a short integer value and stores it in n.

 

basic_istream<charT, traits>& operator >>

 

	(unsigned short & n);

 

basic_istream<charT, traits>& operator >>

 

	(int & n);

 

basic_istream<charT, traits>& operator >>

 

(unsigned int &n);

 

basic_istream<charT, traits>& operator >>

 

	(long & n);

 

basic_istream<charT, traits>& operator >>

 

	(unsigned long & n);

 

basic_istream<charT, traits>& operator >>

 

	(float & f);

 

basic_istream<charT, traits>& operator >>

 

	(double& f);

 

basic_istream<charT, traits>& operator >>(

 

	long double& f);

Remarks:

The Arithmetic extractors extract a specific type from the input

stream and store it in the address provided

States and stdio equivalents:

 

state
stdio equivalent
(flags() & basefield) == oct  

%o  

(flags() & basefield) == hex  

%x  

(flags() & basefield) != 0  

%x  

(flags() & basefield) == 0  

%i  

Otherwise  

 

signed integral type  

%d  

unsigned integral type  

%u  

 

 


27.6.1.2.3 basic_istream extractor operator >>

 

Extracts characters or sequences of characters and converts if

necessary to numerical data.

Prototype:

basic_istream<charT, traits>& operator >>

 

	basic_istream<charT, traits>& (*pf)

 

		(basic_istream<charT,traits>&))


Remarks

 

Returns pf(*this).

 

basic_istream<charT, traits>& operator >>

 

	(basic_ios<charT, traits>& (*pf)

 

	(basic_ios<charT,traits>&))


Remarks

 

Calls pf(*this) then returns *this.

 

basic_istream<charT, traits>& operator >>

 

	(char_type *s);


Remarks

 

Extracts a char array and stores it in s if possible otherwise

call setstate(failbit). If width() is set greater than zero width()-1

elements are extracted else up to size of s-1 elements are extracted.

Scan stops with a whitespace "as if" in fscanf().

 

basic_istream<charT, traits>& operator >>

 

	(char_type& c);


Remarks

 

Extracts a single character and stores it in c if possible otherwise

call setstate(failbit).

 

basic_istream<charT, traits>& operator >>

 

	(void*& p);


Remarks

 

Converts a pointer to void and stores it in p.

 

basic_istream<charT, traits>& operator >>

 

	(basic_streambuf<char_type, traits>* sb);


Remarks

 

Extracts a basic_streambuf type and stores it in sb if possible otherwise call setstate(failbit).

Remarks:

The various overloaded extractors are used to obtain formatted input dependent upon the type of

the argument. Since they return a reference to the calling stream

they may be chained in a series of extractions. The overloaded

extractors work "as if" like fscanf() in standard C and read until a white space character or EOF

is encountered.


NOTE

The white space character is not extracted and is not discarded,

but simply ignored. Be careful when mixing unformatted input operations

with the formatted extractor operators. Such as when using console

input.


Return:

The this pointer is returned.

See Also:

basic_ostream::operator <<

Example of basic_istream:: extractor usage::


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





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

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

	char type[20];
	double d;
	int i;
	char ch;

	in   >> type >> d;
	cout << type << " " << d << endl;
	in   >> type >> d;
	cout << type << " " << d << endl;
	in   >> type >> i;
	cout << type << " " << i << endl;
	in   >> type >> ch;
	cout << type << " " << ch << endl;

	cout << "\nEnter an integer: ";
	cin >> i;
	cout << "Enter a word: ";
	cin >> type;
	cout << "Enter a character \ "
		<< "then a space then a double: ";
	cin >> ch >> d;

	cout << i << " " << type << " " 
		<< ch << " " << d << endl;

	in.close();
 
	return 0;
}





Result:
float 33.33
double 3.16e+10
Integer 789
character C
Enter an integer: 123 <enter>
Enter a word: Metrowerks <enter>
Enter a character then a space then a double: a 12.34 <enter>
123 Metrowerks a 12.34

 



Overloading Extractors:

 

To provide custom formatted data retrieval.

Prototype:

extractor prototype

 

Basic_istream &operator >>

 

	(basic_istream &s,const imanip<T>&)

 

	{

 

		// procedures

 

		return s;

 

	}

Remarks:

You may overload the extractor operator to tailor the specific needs of a particular class.

Return:

The this pointer is returned.

Example of basic_istream overloaded extractor usage::


#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <cstring>
class phonebook {
	friend std::ostream &operator<<(std::ostream &stream,
		phonebook o);
	friend std::istream &operator>>(std::istream &stream,
		phonebook &o);

	private:
	char name[80];
	int areacode;
	int exchange;
	int num;

	public:
	void putname() {std::cout << num;}
	phonebook() {}; 	// default constructor
	phonebook(char *n, int a, int p, int nm)
		{std::strcpy(name, n); areacode = a; 
			exchange = p; num = nm;}
};

int main()
{
using namespace std;
	phonebook a;

	cin >> a;
	cout << a;

	return 0; 
}

std::ostream &operator<<(std::ostream &stream, phonebook o)
{
using namespace std;

	stream << o.name << " ";
	stream << "(" << o.areacode << ") ";
	stream << o.exchange << "-";
	cout << setfill('0') << setw(4) << o.num << "\n";
	return stream;
}

std::istream &operator>>(std::istream &stream, phonebook &o)
{
using namespace std;

	char buf[5];
	cout << "Enter the name: ";
	stream >> o.name;
	cout << "Enter the area code: ";
	stream >> o.areacode;
	cout << "Enter exchange: ";
	stream >> o.exchange;
	cout << "Enter number: ";
	stream >> buf;
	o.num = atoi(buf);
	cout << "\n";
	return stream;
}





Result:
Enter the name: Metrowerks
Enter the area code: 512
Enter exchange: 873
Enter number: 4700
Metrowerks (512) 873-4700

 



27.6.1.3 Unformatted input functions

 

The various unformatted input functions all begin by construction

an object of type basic_istream::sentry and ends by destroying the sentry object.


NOTE

Older versions of the library may begin by calling ipfx() and

end by calling isfx() and returning the value specified.



basic_istream::gcount

 

To obtain the number of bytes read.

Prototype:

streamsize gcount() const;

Remarks:

Use the function gcount() to obtain the number of bytes read by the last unformatted

input function called by that object.

Return:

An int type count of the bytes read.

Example of basic_istream::gcount() usage::


#include <iostream>
#include <fstream>
const SIZE = 4;

struct stArray {
	int index;
	double dNum;
};

int main()
{ 
using namespace std;

	ofstream fOut("test");
	if(!fOut.is_open()) 
		{cout << "can't open out file"; return 1;}

	stArray arr;
	short i; 

	for(i = 1; i < SIZE+1; i++) 
	{
		arr.index = i;
		arr.dNum = i *3.14;
		fOut.write((char *) &arr, sizeof(stArray));
	}
	fOut.close();

	stArray aIn[SIZE];

	ifstream fIn("test");
	if(!fIn.is_open()) 
		{cout << "can't open in file"; return 2;}

	long count =0;
	for(i = 0; i < SIZE; i++) 
	{     fIn.read((char *) &aIn[i], sizeof(stArray));

	count+=fIn.gcount();
	}

	cout << count << " bytes read " << endl;
	cout << "The size of the structure is " 
		<< sizeof(stArray) << endl;
	for(i = 0; i < SIZE; i++)
	cout << aIn[i].index << " " << aIn[i].dNum 
		<< endl;

	fIn.close();

	return 0;
}





Result:
48 bytes read 
The size of the structure is 12
1 3.14
2 6.28
3 9.42
4 12.56

 



basic_istream::get

 

Overloaded functions to retrieve a char or a char sequence from an input stream.

Prototype:

int_type get();


Remarks

 

Extracts a character if available and returns that value. Else,

calls setstate(failbit) and returns eof().

 

basic_istream<charT, traits>& get(char_type& c);


Remarks

 

Extracts a character and assigns it to c if possible else calls setstate(failbit).

 

basic_istream<charT, traits>& get

 

	(char_type* s,

 

	streamsize n, 

 

	char_type delim = traits::newline());


Remarks

 

Extracts characters and stores them in a char array at an address pointed to by s, until

 

  • A limit (the second argument minus one) or the number of characters

    to be stored is reached

  • A delimiter (the default value is the newline character) is met. In which case, the delimiter is not extracted.

  • If end_of_file is encountered in which case setstate(eofbit) is called.

If no characters are extracted calls setstate(failbit). In any case it stores a null character in the next available location of array s.

 

basic_istream<charT, traits>& get

 

	(basic_steambuf<char_type, 

 

	traits>& sb, 

 

	char_type delim = traits::newline());


Remarks

 

Extracts a characters and assigns them to the basic_streambuf object sb if possible else calls setstate(failbit). Extraction stops if...

 

  • an insertion fails
  • end-of-file is encountered.

  • an exception is thrown

  • the next the next available character c == delim (in which case c is not extracted.)

    Return:

An integer when used with no argument. When used with an argument

if a character is extracted the get() function returns The this pointer. If no character is extracted setstate(failbit) is called. In

any case a null char is appended to the array.

See Also:

getline()

Example of basic_istream::get() usage::


READ ONE CHARACTER:
MW Reference file for input
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;
	while(in.get(ch)) cout << ch;

	return 0;
}





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

 


READ ONE LINE:


#include <iostream>

#include <iostream>

 

const int size = 100;

char buf[size];

 

int main()

{

using namespace std;

 

cout << " Enter your name: ";

cin.get(buf, size);

cout << buf;

 

return 0;

}


Result:
Enter your name: Metrowerks CodeWarrior <enter>Metrowerks CodeWarrior

 



basic_istream::getline

 

To obtain a delimiter terminated character sequence from an input

stream.

Prototype:

basic_istream<charT, traits>& getline

 

	(char_type* s, 

 

	streamsize n, 

 

	char_type delim = traits::newline());

Remarks:

The unformatted getline() function retrieves character input, and stores it in a character

array buffer s if possible until the following conditions evaluated in this order occur.

If no characters are extracted setstate(failbit) is called.

 

  • end-of-file occurs in which case setstate(eofbit) is called.

  • A delimiter (default value is the newline character) is encountered.

    In which case the delimiter is read and extracted but not stored.

  • A limit (the second argument minus one) is read.

  • if n-1 chars are read that failbit gets set.

In any case it stores a null char into the next successive location

of the array.

Return:

The this pointer is returned.

See Also:

basic_ostream::flush()

Example of basic_istream::getline() usage::


#include <iostream>
const int size = 120;
int main()
{
using namespace std;

	char compiler[size];

	cout << "Enter your compiler: ";
	cin.getline(compiler, size);

	cout << "You use " << compiler;

	return 0;
}





Result:
Enter your compiler:Metrowerks CodeWarrior <enter>You use Metrowerks CodeWarrior




#include <iostream>
const int size = 120;
#define TAB '\t'

int main()
{
using namespace std;

	cout << "What kind of Compiler do you use: ";
	char compiler[size];


	cin.getline(compiler, size,TAB);
	cout << compiler;
	cout << "\nsecond input not needed\n";
	cin >> compiler;
	cout << compiler;

	return 0;
}





Result:
What kind of Compiler do you use:
Metrowerks CodeWarrior<tab>Why?
Metrowerks CodeWarrior
second input not needed
Why?

 



basic_istream::ignore

 

To extract and discard a number of characters.

Prototype:

basic_istream<charT, traits>& ignore

 

	(steamsize n = 1, 

 

	int_type delim = traits::eof());

Remarks:

The function ignore() will extract and discard characters until

 

  • A limit is met (the first argument)

  • end-of-file is encountered (in which case setstate(eofbit) is called.)

  • The next character c is equal to the delimiter delim, in which case it is extracted

    except when c is equal to traits::eof();Return:

The this pointer is returned.

Example of basic_istream::ignore() usage::


The file MW Reference contains:
char ch;                // to save char
      /*This C comment will remain */ 
while((ch = in.get())!= EOF) cout.put(ch); 
// read until failure
/* the C++ comments won't */ 





#include <iostream>
#include <fstream> 
#include <cstdlib>         
char inFile[] = "MW Reference";
char bslash = '/';

int main()
{
using namespace std;

	ifstream in(inFile);
	if(!in.is_open())
		{cout << "file not opened"; exit(1);}

	char ch;
	while((ch = in.get()) != EOF)
	{
		if(ch == bslash && in.peek() == bslash)
		{
			in.ignore(100, '\n');
			cout << '\n';
		}
		else     cout << ch;
	}

	return 0;
}





Result:
char ch;
      /*This C comment will remain */ 
while((ch = in.get())!= EOF) cout.put(ch); 
/* the C++ comments won't */ 

 



basic_istream::peek

 

To view at the next character to be extracted.

Prototype:

int_type peek();

Remarks:

The function peek() allows you to look ahead at the next character in a stream

to be extracted without extracting it.

Return:

If good() is false returns traits::eof() else returns the value of the next character in the stream.

Example of basic_istream::peek() usage::


See basic_istream::ignore()

 



basic_istream::read

 

To obtain a block of binary data from and input stream.

Prototype:

basic_istream<charT, traits>& read

 

	(char_type* s, streamsize n);

Remarks:

The function read() will attempt to extract a block of binary data until the following

conditions are met.

 

  • A limit of n number of characters are stored.

  • end-of-file is encountered on the input (in which case setstate(failbit) is called.

    Return:

The this pointer is returned.

See Also:

write()

Example of basic_istream::read() usage::


#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdlib>
#include <cstring>
struct stock { 
	char name[80];
	double price;
	long trades;
};

char *Exchange = "BBSE";
char *Company = "Big Bucks Inc.";

int main()
{
using namespace std;

	stock Opening, Closing;

	strcpy(Opening.name, Company);
	Opening.price = 180.25;
	Opening.trades = 581300;

		// open file for output
	ofstream Market(Exchange, ios::out | ios::trunc | ios::binary); 
	if(!Market.is_open()) 
	{cout << "can't open file for output"; exit(1);}

	Market.write((char*) &Opening, sizeof(stock));
 	Market.close();

			// open file for input
	ifstream Market2(Exchange, ios::in | ios::binary);
	if(!Market2.is_open()) 
	{cout << "can't open file for input"; exit(2);}

	Market2.read((char*) &Closing, sizeof(stock));
 
 	cout << Closing.name << "\n"
		<< "The number of trades was: " << Closing.trades << '\n';
	cout << fixed << setprecision(2)
		<< "The closing price is: $" << Closing.price << endl;

	Market2.close();

	return 0;
}





Result:
Big Bucks Inc.
The number of trades was: 581300
The closing price is: $180.25

 



basic_istream::readsome

 

Extracts characters and stores them in an array.

Prototype:

streamsize readsome

 

	(charT_type* s, streamsize n);

Remarks:

The function readsome extracts and stores characters storing them in the buffer pointed

to by s until the following conditions are met.

 

  • end-of-file is encountered (in which case setstate(eofbit) is

    called.)

  • No characters are extracted.

  • A limit of characters is extracted either n or the size of the

    buffer.

    Return:

The number of characters extracted.

Example of basic_istream::readsome() usage.:


The file MW Reference contains:
Metrowerks CodeWarrior
Software at Work
Registered Trademark





#include <iostream>
#include <fstream>
#include <sstream>
#include <cstdlib>
const short SIZE = 81;

int main()
{	 
using namespace std;

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

 	char Buffer[SIZE] = "\0";
 	ostringstream Paragraph;
 	
	while(in.good() && (in.peek() != EOF))
	{
		in.readsome(Buffer, 5);	
		Paragraph << Buffer;
 	}

	cout << Paragraph.str();
	
	in.close();
	return 0;
}





Result:
Metrowerks CodeWarrior
Software at Work
Registered Trademark

 



basic_istream::putback

 

To replace a previously extracted character.

Prototype:

basic_istream<charT, traits>& putback

 

	(char_type c);

Remarks:

The function putback() allows you to replace the last character extracted by calling rdbuf()->sungetc(). If the buffer is empty, or if sungetc() returns eof, setstate(failbit) may be called.

Return:

The this pointer is returned.

See Also:

sungetc()

Example of basic_istream::putback usage::


The file MW Reference contains.
char ch;                // to save char
      /* comment will remain */ 
while((ch = in.get())!= EOF) cout.put(ch); 
// read until failure





#include <iostream>
#include <fstream> 
#include <stdlib.h>
char inFile[] = "MW Reference";
char bslash = '/';

int main()
{
using namespace std;

	ifstream in(inFile);
	if(!in.is_open()) 
	{cout << "file not opened"; exit(1);}
       
	char ch, tmp;
	while((ch = in.get()) != EOF)
	{
		if(ch == bslash)
		{
			in.get(tmp);
			if(tmp != bslash)
				in.putback(tmp);
			else continue;
		}                 
		cout << ch;
	}
         
	return 0;
}





Result:
char ch;                 to save char
      /* comment will remain */ 
while((ch = in.get())!= EOF) cout.put(ch); 
 read until failure

 



basic_istream::unget

 

To replace a previously extracted character.

Prototype:

basic_istream<charT, traits>&unget();

Remarks:

Use the function unget() to return the previously extracted character. If rdbuf() is null or if end-of-file is encountered setstate(badbit) is called.

Return:

The this pointer is returned.

See Also:

putback(), ignore()

Example of basic_istream::unget() usage::


The file MW Reference contains:
char ch;                // to save char
        /* comment will remain */ 
         // read until failure
while((ch = in.get()) != EOF) cout.put(ch); 





#include <iostream>
#include <fstream>
#include <cstdlib>
char inFile[] = "MW Reference";
char bslash = '/';

int main()
{
using namespace std;

	ifstream in(inFile);
	if(!in.is_open()) 
	{cout << "file not opened"; exit(1);}

	char ch, tmp;
	while((ch = in.get()) != EOF)
	{
	if(ch == bslash)
	{
		in.get(tmp);
		if(tmp != bslash)
			in.unget();
			else continue;
		} 
	cout << ch;
	}

	return 0;
}





Result:
char ch;                 to save char
        /* comment will remain */ 
          read until failure
while((ch = in.get()) != EOF) cout.put(ch); 

 



basic_istream::sync

 

To synchronize input and output

Prototype:

int sync();

Remarks:

This functions attempts to make the input source consistent with

the stream being extracted.

 

If rdbuf()->pubsync() returns -1 setstate(badbit) is called and traits::eof is returned.

Return:

If rdbuf() is Null returns -1 otherwise returns zero.

Example of basic_istream::sync() usage::


The file MW Reference contains:
This functions attempts to make the input source 
consistent with the stream being extracted.
--
Metrowerks CodeWarrior "Software at Work"





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

int main()
{ 
using namespace std;

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

	char str[10];
	if(in.sync())		// return 0 if successful
		{ cout << "cannot sync"; exit(1); } 
	while (in.good())
	{
		in.get(str, 10, EOF);
		cout <<str; 
	}
	return 0;
} 





Result:
This functions attempts to make the input source 
consistent with the stream being extracted.
--
Metrowerks CodeWarrior "Software at Work"

 



basic_istream::tellg

 

To determine the offset of the get pointer in a stream

Prototype:

pos_type tellg();

Remarks:

The function tellg calls rdbuf()->pubseekoff(0, cur, in).

Return:

The current offset as a pos_type if successful else returns -1.

See Also:

basic_streambuf::pubseekoff()

Example of basic_istream::tellg() usage::


See basic_istream::seekg()

 



basic_istream::seekg

 

To move to a variable position in a stream.

Prototype:

basic_istream<charT, traits>& seekg(pos_type);

 

basic_istream<charT, traits>& seekg

 

(off_type, ios_base::seekdir dir);

Remarks:

The function seekg is overloaded to take a pos_type object, or an off_type object (defined in basic_ios class.) The function is used to set the position of the get pointer of a stream to a random location for character extraction.

Return:

The this pointer is returned.

See Also:

basic_streambuf::pubseekoff() and pubseekpos().

Example of basic_istream::seekg() usage::


The file MW Reference contains:
ABCDEFGHIJKLMNOPQRSTUVWXYZ





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

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

// note streampos is typedef in iosfwd
	streampos spEnd(5), spStart(5);

	in.seekg(spStart);
	streampos aCheck = in.tellg();
	cout << "The offfset at the start of the reading in bytes is " 
		<< aCheck << endl; 

	char ch;
	while(spEnd != spStart+10) 
	{
		in.get(ch);
		cout << ch;
		spEnd = in.tellg();
	}

	aCheck = in.tellg();
	cout << "\nThe current position's offset in bytes now is " 
		<< aCheck << endl; 
	streamoff gSet = 0;     
	in.seekg(gSet, ios::beg);

	aCheck = in.tellg();
	cout << "The final position's offset in bytes now is " 
	<< aCheck << endl; 

	in.close();
	return 0;
}

 



Result:
The offfset at the start of the reading in bytes is 5FGHIJKLMNOThe current position's offset in bytes now is 15The final position's offset in bytes now is 0

 



27.6.1.4 Standard basic_istream manipulators


basic_ifstream::ws

 

To provide inline style formatting.

Prototype:

template

 

	<class charT, class traits>

 

basic_istream<charT, traits> &ws

 

	(basic_istream<charT,traits>& is);

Remarks:

The ws manipulator skips whitespace characters in input.

Return:

The this pointer.

Example of basic_istream:: manipulator ws usage::


The file MW Reference (where the number of blanks (and/or tabs) 
is unknown) contains:
		a   	  b   c





#include <iostream>
#include <fstream>
#include <cstdlib>
int main()
{
	char * inFileName = "MW Reference";

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

	char ch;
	in.unsetf(ios::skipws);
	
	cout << "Does not skip whitespace\n|";
	while (1)
	{
		in >> ch; // does not skip white spaces
		if (in.good())
			cout << ch;
		else break;
	}
	cout << "|\n\n";
	
	//reset file position
	in.clear(); 
	in.seekg(0, ios::beg);
	
	cout << "Does skip whitespace\n|";
	while (1)
	{
		in >> ws >> ch;  // ignore white spaces
		
		if (in.good())
			cout << ch;
		else break;
	}
	cout << "|" << endl;
		
	
	in.close();
	return(0);
}





Result:
Does not skip whitespace
|       a         b   c|
Does skip whitespace
|abc|

 



27.6.1.4.1 basic_iostream Constructor


Constructor

 

Constructs an and destroy object of the class basic_iostream.

Prototype:

explicit basic_iostream

 

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

Remarks:

Calls basic_istream(<charT, traits> (sb) and basic_ostream(charT, traits>* (sb). After it is constructed rdbuf() equals sb and gcount() equals zero.


Destructor

Prototype:

virtual ~basic_iostream();

Remarks:

Destroys an object of type basic_iostream.


27.6.2 Output streams

 

The include file <ostream> includes classes and types that provide

output stream mechanisms.

 

The topics in this section are:

 


27.6.2.1 Template class basic_ostream

 

A class for stream output mechanisms.

Prototype:


namespace std{
template 
	<class charT, class traits = ios_traits<charT> >
class basic_ostream : virtual public basic_ios<charT, traits>{
	public:
	// Types:
	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;
	explicit basic_ostream (basic_streambuf<char_type, traits>*sb);
	virtual ~basic_ostream();

	class sentry;

	basic_ostream<charT, traits>& operator<<
		(basic_ostream<charT, traits>&(*pf)
			(basic_ostream<charT, traits>&));
	basic_ostream<charT, traits>& operator<<
		(basic_ostream<charT, traits>&(*pf)
			(basic_ios<charT, traits>&));
	basic_ostream<charT, traits>& operator<<
		(const char_type *s)
	basic_ostream<charT, traits>& operator<<
		(char_type c)
	basic_ostream<charT, traits>& operator<<
		(bool n)
	basic_ostream<charT, traits>& operator<<
		(short n)
	basic_ostream<charT, traits>& operator<<
		(unsigned short n)
	basic_ostream<charT, traits>& operator<<
		(int n)
	basic_ostream<charT, traits>& operator<<
		(unsigned int n)
	basic_ostream<charT, traits>& operator<<
		(long n)
	basic_ostream<charT, traits>& operator<<
		(unsigned long n)
	basic_ostream<charT, traits>& operator<<
		(float f)
	basic_ostream<charT, traits>& operator<<
		(double f)
	basic_ostream<charT, traits>& operator<<
		(long double f)
	basic_ostream<charT, traits>& operator<<
		(void p)
	basic_ostream<charT, traits>& operator<<
		(basic_streambuf>char_type, traits>* sb);)

	basic_ostream<charT, traits>& put(char_type c);

	basic_ostream<charT, traits>& write
		(const char_type* s, streamsize n);

	basic_ostream<charT, traits>& flush();

	pos_type tellp();
	basic_ostream<charT, traits>& seekp(pos_type);
	basic_ostream<charT, traits>& seekp
		(off_type, ios_base::seekdir);
};
}

 


Remarks:

The basic_ostream class provides for output stream mechanisms

for output stream classes. The basic_ostream class may be used

as a independent class, as a base class for the basic_ofstream

class or a user derived classes.


27.6.2.2 basic_ostream Constructor

 

To create and remove from memory basic_ostream object for stream

output.

Prototype:

explicit basic_ostream

 

	(basic_streambuf<char_type, traits>*sb);

Remarks:

The basic_ostream constructor constructs and initializes the base class object.


Destructor

Prototype:

virtual ~basic_ostream();

Remarks:

Removes a basic_ostream object from memory.

Example of basic_ostream() usage::


The MW Reference file contains originally
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 << "Could not open file"; exit(1);}
	ostream Out(inOut.rdbuf());

	char str[] = "\nRegistered Trademark";

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

	Out << str;

	inOut.close();
	
	return 0;
}





Result:
The File now reads:
Metrowerks CodeWarrior "Software at Work"
Registered Trademark

 



27.6.2.3 Class basic_ostream::sentry

 

A class for exception safe prefix and suffix operations.

Prototype:

namespace std {

 

template

 

	< class charT, 

 

	class traits = char_traits<charT> > 

 

class basic_ostream<chartT, traits>::sentry 

 

{

 

	bool ok_;

 

	public:

 

	explicit sentry

 

		(basic_ostream<charT, 

 

		traits>& os,

 

		bool noskipws = false);

 

	~sentry();

 

	operator bool() {return ok_;}

 

};

 

}


Class basic_ostream::sentry Constructor


Constructor

 

Prepare for formatted or unformatted output

Prototype:

explicit sentry

 

	(basic_ostream<charT, traits>& os);

Remarks:

If after the operation os.good() is true ok_ equals true otherwise ok_ equals false. The constructor may call setstate(failbit) which may throw an exception.


Destructor

Prototype:

~sentry();

Remarks:

The destructor under normal circumstances will call os.flush().


sentry::Operator bool

 

To return the value of the data member ok_.

Prototype :

operator bool();

Return:

Operator bool returns the value of ok_


27.6.2.4 Formatted output functions

 

Formatted output functions provide a manner of inserting for

output specific data types.


27.6.2.4.1 Common requirements

Remarks:

The operations begins by calling opfx() and ends by calling osfx()

then returning the value specified for the formatted output.

 

Some output maybe generated by converting the scalar data type

to a NTBS (null terminated bit string) text.

 

If the function fails for any for any reason the function calls

setstate(failbit).


27.6.2.4.2 Arithmetic Inserter Operator <<

 

To provide formatted insertion of types into a stream.

Prototype:

basic_ostream<charT, traits>& operator<<

 

	(short n)

 

basic_ostream<charT, traits>& operator<<

 

	(unsigned short n)

 

basic_ostream<charT, traits>& operator<<

 

	(int n)

 

basic_ostream<charT, traits>& operator<<

 

(unsigned int n)

 

basic_ostream<charT, traits>& operator<<

 

	(long n)

 

basic_ostream<charT, traits>& operator<<

 

	(unsigned long n)

 

basic_ostream<charT, traits>& operator<<

 

	(float f)

 

basic_ostream<charT, traits>& operator<< 

 

	(double f)

 

basic_ostream<charT, traits>& operator<<

 

	(long double f)

Remarks:

Converts an arithmetical value.The formatted values are converted "as if" they had the same behavior of the fprintf() function

Return:

The this pointer is returned

Output states and stdio equivalents.:

 

Output State
stdio equivalent
Integers  

 

(flags() & basefield) == oct  

%o  

(flags() & basefield) == hex  

%x  

(flags() & basefield) != 0  

%x  

Otherwise  

 

signed integral type  

%d  

unsigned integral type  

%u  

Floating Point Numbers  

 

(flags() & floatfield) == fixed  

%f  

(flags() & floatfield) == scientific   (flags() & uppercase) != 0  

%e   %E  

Otherwise  

 

(flags() & uppercase) != 0  

%g %G  

An integral type other than   a char type  

 

(flags() & showpos) != 0   (flags() & showbase) != 0  

+   #  

A floating point type  

 

(flags() & showpos) != 0   (flags() & showpoint) != 0  

+   #  

 

 

 

For any conversion if width() is non-zero then a field width a conversion specification has

the value of width().

 

For any conversion if (flags() and fixed) !=0 or if precision() >0 the conversion specification is the value of precision().

 

For any conversion padding behaves in the following manner.

Conversion state and stcio equivalents.:

 

State
Justification
stdio equivalent
(flags()& adjustfield) == left  

left  

space padding  

(flags() & adjustfield) == internal  

Internal  

zero padding  

Otherwise  

right  

space padding  

 

 

Remarks:

The ostream insertion operators are overloaded to provide for insertion of

most predefined types into and output stream. They return a reference

to the basic stream object so they may be used in a chain of statements to input

various types to the same stream.

Return:

In most cases *this is returned unless failure in which case

setstate(failbit) is called.


27.6.2.4.3 basic_ostream::operator<<

Prototype:

basic_ostream<charT, traits>& operator<<

 

	(basic_ostream<charT, traits>&

 

		(*pf)(basic_ostream<charT, traits>&));


Remarks

 

Returns pf(*this).

 

basic_ostream<charT, traits>& operator<<

 

	(basic_ostream<charT, traits>&

 

		(*pf)(basic_ios<charT, traits>&));


Remarks

 

Calls pf(*this) return *this.

 

basic_ostream<charT, traits>& operator<<

 

	(const char_type *s)

 

basic_ostream<charT, traits>& operator<<

 

	(char_type c)

 

basic_ostream<charT, traits>& operator<<

 

	(bool n)


Remarks

 

Behaves depending on how the boolalpha flag is set.

 

basic_ostream<charT, traits>& operator<<

 

	(void p)


Remarks

 

Converts the pointer to void p as if the specifier was %p and returns *this.

 

basic_ostream<charT, traits>& operator<<

 

	(basic_streambuf>char_type, traits>* sb);)


Remarks

 

If sb is null calls setstate(failbit) otherwise gets characters from sb and inserts them into *this

until:

 

  • end-of-file occurs.

  • inserting into the stream fails.

  • an exception is thrown.

If the operation fails calls setstate(failbit) or re-throws the exception, otherwise returns *this.

Remarks:

The formatted output functions insert the values into the appropriate

argument type.

Return:

Most inserters (unless noted otherwise) return the this pointer.

Example of basic_ostream inserter usage::


#include <iostream>
#include <fstream>
#include <cstdlib>
char oFile[81] = "MW Reference";

int main() 
{
using namespace std;

	ofstream out(oFile);

	out << "float " << 33.33;
	out << " double " << 3.16e+10;
	out << " Integer " << 789;
	out << " character " << 'C' << endl;
	out.close();

	cout << "float " << 33.33;
	cout << "\ndouble " << 3.16e+10;
	cout << "\nInteger " << 789;
	cout << "\ncharacter " << 'C' << endl;

	return 0;
}





Result:
Output: to MWReference
float 33.33 double 3.16e+10 Integer 789 character C
Output to console
float 33.33
double 3.16e+10
Integer 789
character C

 



Overloading Inserters

 

To provide specialized output mechanisms for an object.

Prototype:

Overloading inserter prototype

 

basic_ostream &oerator<<

 

	(basic_ostream &stream,const omanip<T>&)

 

	{

 

		// procedures;

 

		return stream;

 

	} 

Remarks:

You may overload the inserter operator to tailor it to the specific

needs of a particular class.

Return:

The this pointer.

Example of overloaded inserter usage::


#include <iostream>
#include <string.h>
#include <iomanip>
class phonebook {
	friend ostream &operator<<
		(ostream &stream, phonebook o);
protected:                
	char *name;
	int areacode;
	int exchange;
	int num;
public:
	phonebook(char *n, int a, int p, int nm) :
		areacode(a), 
		exchange(p), 
		num(nm), 
		name(n) {}
};

int main()
{
using namespace std;

	phonebook a("Sales", 800, 377, 5416);
	phonebook b("Voice", 512, 873, 4700);
	phonebook c("Fax",   512, 873, 4900);

	cout << a << b << c;

	return 0; 
}
     
std::ostream &operator<<(std::ostream &stream, phonebook o)
{
	stream << o.name << " ";
	stream << "(" << o.areacode << ") ";
	stream << o.exchange << "-";
	stream << setfill('0') << setw(4) 
		<< o.num << "\n";
	return stream;
}





Result:
Sales (800) 377-5416
Voice (512) 873-4700
Fax (512) 873-4900

 


27.6.2.5 Unformatted output functions

 

Each unformatted output function begins by creating an object

of the class sentry. The unformatted output functions are ended

by destroying the sentry object and may return a value specified.


basic_ostream::tellp

 

To return the offset of the put pointer in an output stream.

Prototype:

pos_type tellp(); 

Return:

If fail() returns -1 else returns rdbuf()->pubseekoff(0, cur, out).

See Also :

basic_istream::tellg(), seekp(0).

Example of basic_ostream::tellp() usage.:


see basic_ostream::seekp().

 



basic_ostream::seekp

 

Randomly move to a position in an output stream.

Prototype:

basic_ostream<charT, traits>& seekp(pos_type);

Prototype:

basic_ostream<charT, traits>& seekp

 

		(off_type, iosbase::seekdir);

Remarks:

The function seekp is overloaded to take a single argument of a pos_type pos that calls rdbuf()->pubseekpos(pos). It is also overloaded to take two arguments an off_type off and ios_base::seekdir type dir that calls rdbuf()->pubseekoff(off, dir).

Return:

The this pointer.

See Also:

basic_istream seekg(), tellp()

Example of basic_ostream::seekp() usage.:


#include <iostream>
#include <sstream>
#include <string>
std::string motto = "Metrowerks CodeWarrior - Software at Work"; 

int main()
{ 
using namespace std;

	ostringstream ostr(motto); 
	streampos cur_pos, start_pos;

	cout << "The original array was :\n" 
		<< motto << "\n\n"; 
		// associate buffer
	stringbuf *strbuf(ostr.rdbuf()); 
	
	streamoff str_off = 10; 
	cur_pos = ostr.tellp();
	cout << "The current position is " 
	     << cur_pos.offset()
	     << " from the beginning\n";

	ostr.seekp(str_off); 

	cur_pos = ostr.tellp(); 
	cout << "The current position is " 
	     << cur_pos.offset() 
	     << " from the beginning\n";

	strbuf->sputc('\0');

	cout << "The stringbuf array is\n" 
		<< strbuf->str() << "\n\n";
	cout << "The ostringstream array is still\n" 
		<< motto;
 
	return 0;
}





Results:
The original array was :
Metrowerks CodeWarrior - Software at Work
The current position is 0 from the beginning
The current position is 10 from the beginning
The stringbuf array is
Metrowerks

The ostringstream array is still
Metrowerks CodeWarrior - Software at Work

 



basic_ostream::put

 

To place a single character in the output stream.

Prototype:

basic_ostream<charT, traits>& put(char_type c);

Remarks:

The unformatted function put() inserts one character in the output stream. If the operation

fails calls setstate(badbit).

Return:

The this pointer.

Example of basic_ostream::put() usage::

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

	char *str = "Metrowerks CodeWarrior \"Software at Work\"";
	while(*str) 
	{ 
		cout.put(*str++);
	}
	return 0;
}





Result:
Metrowerks CodeWarrior "Software at Work"

 



basic_ostream::write

 

To insert a block of binary data into an output stream.

Prototype:

basic_ostream<charT, traits>& write

 

	(const char_type* s, streamsize n);

Remarks:

The overloaded function write() is used to insert a block of binary data into a stream. This

function is can be used to write an object by casting that object

as a unsigned char pointer. If the operation fails calls setstate(badbit).

Return:

A reference to ostream. (The this pointer.)

See Also:

read()

Example of basic_ostream::write() usage::


#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdlib>
#include <cstring>
struct stock { 
	char name[80];
	double price;
	long trades;
};

char *Exchange = "BBSE";
char *Company = "Big Bucks Inc.";

int main()
{
using namespace std;

	stock Opening, Closing;

	strcpy(Opening.name, Company);
	Opening.price = 180.25;
	Opening.trades = 581300;

		// open file for output
	ofstream Market(Exchange, 
			ios::out | ios::trunc | ios::binary); 
	if(!Market.is_open()) 
	{cout << "can't open file for output"; exit(1);}

	Market.write((char*) &Opening, sizeof(stock));
 	Market.close();

			// open file for input
	ifstream Market2(Exchange, ios::in | ios::binary);
	if(!Market2.is_open()) 
	{cout << "can't open file for input"; exit(2);}

	Market2.read((char*) &Closing, sizeof(stock));

	cout << Closing.name << "\n"
		<< "The number of trades was: " 
		<< Closing.trades << '\n';
	cout << fixed << setprecision(2)
		<< "The closing price is: $" 
		<< Closing.price << endl;

	Market2.close();

	return 0;
}





Result:
Big Bucks Inc.
The number of trades was: 581300
The closing price is: $180.25

 



basic_ostream::flush

 

To force the output buffer to release its contents.

Prototype:

basic_ostream<charT, traits>& flush();

Remarks:

The function flush() is an output only function in C++. You may use it for an immediate

expulsion of the output buffer. This is useful when you have critical

data or you need to ensure that a sequence of events occurs in

a particular order. If the operation fails calls setstate(badbit).

Return:

The this pointer.

Example of basic_ostream::flush() usage::


#include <iostream>
#include <iomanip>
#include <ctime>
class stopwatch {
private:
	double begin, set, end;   
public:
	stopwatch();
	~stopwatch();
	void start();
	void stop();
};

stopwatch::stopwatch() 
{    
using namespace std;
           
	begin = (double) clock() / CLOCKS_PER_SEC; 
	end   = 0.0; 
	start();
	cout << "begin the timer: ";
}

stopwatch::~stopwatch() 
{
using namespace std;

	stop(); 	// set end
	cout << "\nThe Object lasted: ";
	cout << fixed << setprecision(2)
		<< end - begin << " seconds \n";
}

// clock ticks divided by ticks per second
void stopwatch::start() 
{
using namespace std;

	set = double(clock()/CLOCKS_PER_SEC);
}

void stopwatch::stop() 
{
using namespace std;

	end = double(clock()/CLOCKS_PER_SEC);
}

void time_delay(unsigned short t);

int main()
{
using namespace std;

	stopwatch watch; // create object and initialize 
	cout.flush(); // this flushes the buffer 
	time_delay(5);    
	return 0; // destructor called at return
}
		//time delay function
void time_delay(unsigned short t)
{
using namespace std;

	time_t tStart, tEnd;
	time(&tStart);
	while(tStart + t > time(&tEnd)){};
}





Result:
Note:  comment out the flush and both lines will display simultaneously at the end of the program.
begin the timer: < immediate display then pause >begin the timer: 
The Object lasted: 3.83 seconds

 



27.6.2.6 Standard basic_ostream manipulators

 

To provide an inline formatting mechanism.


basic_ostream:: endl

 

To insert a newline and flush the output stream.

Prototype:

template

 

	< class charT, class traits >

 

basic_ostream<charT, traits> & endl

 

	(basic_ostream<charT,traits>& os);

Remarks:

The manipulator endl takes no external arguments, but is placed

in the stream. It inserts a newline character into the stream

and flushes the output.

Return:

A reference to basic_ostream. (The this pointer.)

See Also:

ostream:: operators


basic_ostream::ends

 

To insert a NULL character.

Prototype:

template

 

	< class charT, class traits >

 

basic_ostream<charT, traits> &ends

 

	(basic_ostream<charT,traits>& os);

Remarks:

The manipulator ends, takes no external arguments, but is placed

in the stream. It inserts a NULL character into the stream, usually

to terminate a string.

Return:

A reference to ostream. (The this pointer)


NOTE

The ostringstream provides in-core character streams but must

be null terminated by the user. The manipulator ends provides

a null terminator.


Example of basic_ostream:: ends usage::

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

	ostringstream out;  // see note above
	out << "Ask the teacher anything\n";
	out << "OK, what is 2 + 2?\n";
	out << 2 << " plus " << 2 << " equals " 
		<< 4 << ends;

	cout << out.str();
	return 0;
}





Result:
Ask the teacher anything
OK, what is 2 + 2?
2 plus 2 equals 4?
		
 



basic_ostream::flush

 

To flush the stream for output.

Prototype:

template<class charT, class traits>
		
 

	basic_ostream<charT, traits> &
		
 

		flush(basic_ostream<charT,traits> (os);
		
Remarks:

The manipulator flush, takes no external arguments, but is placed in the stream. The

manipulator flush will attempt to release an output buffer for

immediate use without waiting for an external input.

Return:

A reference to ostream. (The this pointer.)

See Also:

ostream::flush()

Example of basic_ostream:: flush usage::


#include <iostream>
#include <iomanip>
#include <ctime>
class stopwatch {
private:
	double begin, set, end;   
public:
	stopwatch();
	~stopwatch();
	void start();
	void stop();
};

stopwatch::stopwatch() 
{ 
using namespace std;
              
	begin = (double) clock() / CLOCKS_PER_SEC; 
	end   = 0.0; 
	start();
	{               
	begin = (double) clock() / CLOCKS_PER_SEC; 
	end   = 0.0; 
	start();
	cout << "begin time the timer: " << flush;
} 
}

stopwatch::~stopwatch() 
{
using namespace std;
 
 	stop(); 	// set end
	cout << "\nThe Object lasted: ";
	cout << fixed << setprecision(2)
		<< end - begin << " seconds \n";
}

// clock ticks divided by ticks per second
void stopwatch::start() 
{
using namespace std;
 
 	set = double(clock()/CLOCKS_PER_SEC);
}

void stopwatch::stop() 
{
using namespace std;
 
 	end = double(clock()/CLOCKS_PER_SEC);
}

void time_delay(unsigned short t);

int main()
{
using namespace std;
 
 	stopwatch watch; // create object and initialize 
	time_delay(5);    
	return 0; // destructor called at return
}
		//time delay function
void time_delay(unsigned short t)
{
using namespace std;
 
 	time_t tStart, tEnd;
	time(&tStart);
	while(tStart + t > time(&tEnd)){};
}





Results:
Note: comment out the flush and both lines display simultaneously at the end of the program.
begin time the timer:
< short pause >
The Object lasted: 3.78 seconds
		
 



27.6.3 Standard manipulators

 

The include file iomanip defines a template classes and related functions for input and

output manipulation.


Standard Manipulator Instantiations

 

To create a specific use instance of a template by replacing

the parameterized elements with pre-defined types.


resetiosflags

 

To unset previously set formatting flags.

Prototypes:

smanip resetiosflags(ios_base::fmtflags mask)
		
Remarks:

Use the manipulator resetiosflags directly in a stream 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:

A smanip type, that is an implementation defined type.

See Also:

ios_base::setf(), ios_base::unsetf()

Example of resetiosflags() usage::


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

	double d = 2933.51;
	long flags;
	flags = ios::scientific | ios::showpos | ios::showpoint;
	
	cout << "Original: " << d << endl;
	cout << "Flags set: " << setiosflags(flags) 
		<< d << endl;
	cout << "Flags reset to original: "
		<< resetiosflags(flags) << d << endl;

	return 0;
}




Result:
Original:  2933.51
Flags set:  +2.933510e+03
Flags reset to original:  2933.51
		
 



setiosflags

 

Set the stream format flags.

Prototypes:

smanip setiosflags(ios_base::fmtflags mask)
		
Remarks:

Use the manipulator setiosflags() to set the input and output formatting flags directly in the

stream.

Return:

A smanip type, that is an implementation defined type.

See Also:

ios_base::setf(), ios_base::unsetf()

Example of setiosflags() usage::


See resetiosflags()
		
 



:setbase

 

To set the numeric base of an output.

Prototypes:

smanip setbase(int)
		
Remarks:

The manipulator setbase() directly sets the numeric base of integral output to the stream.

The arguments are in the form of 8, 10, 16, or 0. 8 octal, 10

decimal and 16 hexadecimal. Zero represents ios::basefield, a combination of all three.

Return:

A smanip type, that is an implementation defined type.

See Also:

ios_base::setf()

Example of setbase usage::


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

	cout << "Hexadecimal "
		<< setbase(16) << 196 << '\n';
	cout << "Decimal " << setbase(10) 		<< 196 << '\n';
	cout << "Octal " <<setbase(8) << 196 << '\n';

	cout.setf(ios::hex, ios::oct | ios::hex);
	cout << "Reset to Hex " << 196 << '\n';
	cout << "Reset basefield setting "
		<< setbase(0) << 196 << endl;

	return 0;
}





Result:
Hexadecimal c4
Decimal 196
Octal 304
Reset to Hex c4
Reset basefield setting 196
		
 



setfill

 

To specify the characters to used to insert in unused spaces

in the output.

Prototypes:

smanip setfill(int c)		
		
Remarks:

Use the manipulator setfill() directly in the output to fill blank spaces with character c.

Return:

A smanip type, that is an implementation defined type.

See Also:

basic_ios::fill

Example of basic_ios::setfill() usage::


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

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

	return 0;
}





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



setprecision

 

Set and return the current format precision.

Prototypes:

smanip<int> setprecision(int) 
		
Remarks:

Use the manipulator setprecision() directly in the output stream with floating point numbers to

limit the number of digits. You may use setprecision() with scientific or non-scientific floating point numbers.

 

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:

A smanip type, that is an implementation defined type.

See Also:

ios_base::setf(), ios_base::precision()

Example of setprecision() usage::


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

	cout << "Original: " << 321.123456 <<   endl;
	cout << "Precision set: " << setprecision(8)
		<< 321.123456 <<   endl;
	return 0;
}





Result:
Original:  321.123
Precision set:  321.12346
		
 



setw

 

To set the width of the output field.

Prototypes:

smanip<int> setw(int)		 
		
Remarks:

Use the manipulator setw() directly in a stream to set the field size for output.

Return:

A pointer to ostream

See Also:

ios_base::width()

Example of setw() usage: :


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

	cout << setw(8) 
		<< setfill('*')
		<< "Hi!" << endl;
	return 0;
}





Result:
Hi!*****
		
 



Overloaded Manipulator

 

To store a function pointer and object type for input.

Prototype:

Overloaded input manipulator for int type.

 

istream &imanip_name
		
 

	(istream &stream, type param)
		
 

{
		
 

	// body of code
		
 

	return stream;
		
 

}
		

Overloaded output manipulator for int type.

 

ostream &omanip_name
		
 

	(ostream &stream, type param)
		
 

{
		
 

 // body of code
		
 

 return stream;
		
 

}
		

For other input/output types

 

smanip<type> mainip_name(type param) 
		
 

{
		
 

	return smanip<type> (manip_name, param);
		
 

}
		
Remarks :

Use an overloaded manipulator to provide special and unique input

handling characteristics for your class.

Return:

A pointer to stream object.

Example of overloaded manipulator usage::


#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cctype>
char buffer[80];
char *Password = "Metrowerks";

struct verify
{
	explicit verify(char* check) : check_(check) {}
	char* check_;
};

char *StrUpr(char * str);
std::istream& operator >> (std::istream& stream, const verify& v);

int main()
{
using namespace std;

	cin >> verify(StrUpr(Password));
	cout << "Log in was Completed ! \n";

	return 0; 
}

std::istream& operator >> (std::istream& stream, const verify& v) 
{
using namespace std;

	short attempts = 3;

	do {
		cout << "Enter password: ";
		stream >> buffer;

		StrUpr(buffer);
		if (! strcmp(v.check_, buffer)) return stream;
		cout << "\a\a";
		attempts--;
	} while(attempts > 0);

	cout << "All Tries failed \n";
	exit(1);
	return stream; 
}

char *StrUpr(char * str)
{
	char *p = str; // dupe string
	while(*p) *p++ = static_cast<char>(std::toupper(*p));
	return str;
}





Result:
Enter password: <codewarrior>
Enter password: <mw>
Enter password: <metrowerks>
Log in was Completed ! 
		
 


 

 

 


[ 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