C++ Programming Module18 Tenouk
C++ Programming Module18 Tenouk
Abilities
▪ To understand and use various member functions for C++ formatted I/O.
▪ To understand and use various stream manipulators for C++ formatted I/O.
- In Module 5 you have learned the formatted I/O in C by calling various standard functions. In this
Module we will discuss how this formatted I/O implemented in C++ by using member functions and
stream manipulators.
- If you have completed this Tutorial #3 until Module 17, you should be familiar with class object. In
C++ we will deal a lot with classes. It is readily available for us to use.
- We will only discuss the formatted I/O here, for file I/O and some of the member functions mentioned
in this Module, will be presented in another Module. The discussion here will be straight to the point
because some of the terms used in this Module have been discussed extensively in Module 5.
- The header files used for formatted I/O in C++ are:
- The compilers that fully comply with the C++ standard that use the template based header files won’t
need the .h extension. Please refer to Module 23 for more information.
- The iostream class hierarchy is shown below. From the base class ios, we have a derived class:
- So, iostream support both stream input and output. The class hierarchy is shown below.
www.tenouk.com
18.2 Left and Right Shift Operators
- We have used these operators in most of the Modules in this Tutorial for C++ codes.
- The left shift operator (<<) is overloaded to designate stream output and is called stream insertion
operator.
- The right shift operator (>>) is overloaded to designate stream input and is called stream extraction
operator.
- These operators used with the standard stream object (and with other user defined stream objects) is
listed below:
- For file processing C++ uses (will be discussed in another Module) the following classes:
void main(void)
{
cout<<"Welcome to C++ I/O module!!!"<<endl;
cout<<"Welcome to ";
cout<<"C++ module 18"<<endl;
//endl is end line stream manipulator
//issue a new line character and flushes the output buffer
//output buffer may be flushed by cout<<flush; command
system("pause");
}
Output:
www.tenouk.com
//concatenating <<
#include <stdlib.h>
//for system(), if compiled in some compiler
//such as Visual Studio, no need this stdlib.h
#include <iostream.h>
void main(void)
{
int p = 3, q = 10;
Output:
#include <stdlib.h>
#include <iostream.h>
void main(void)
{
int p, q, r;
Output:
www.tenouk.com
- For the get() function, we have three versions.
1. get() without any arguments, input one character from the designated streams including
whitespace and returns this character as the value of the function call. It will return EOF when
end of file on the stream is encountered. For example:
cin.get();
2. get() with a character argument, inputs the next character from the input stream including
whitespace. It return false when end of file is encountered while returns a reference to the
istream object for which the get member function is being invoked. For example:
char ch;
...
cin.get(ch);
3. get() with three arguments, a character array, a size limit and a delimiter (default value
‘\n’). It reads characters from the input stream, up to one less than the specified maximum
number of characters and terminates or terminates as soon as the delimiter is read. For
example:
char namevar[30];
...
cin.get(namevar, 30);
//get up to 29 characters and inserts null
//at the end of the string stored in variable
//namevar. If a delimiter is found,
//the read terminates. The delimiter
//is left in the stream, not stored
//in the array.
4. getline() operates like the third get() and insert a null character after the line in the
character array. It removes the delimiter from the stream, but does not store it in the character
array.
- Program examples:
#include <stdlib.h>
#include <iostream.h>
void main(void)
{
char p;
Output:
www.tenouk.com
//Another get() version
#include <stdlib.h>
#include <iostream.h>
void main(void)
{
char bufferOne[SIZE], bufferTwo[SIZE];
Output:
//getline() example
#include <stdlib.h>
#include <iostream.h>
void main(void)
{
char buffer[SIZE];
Output:
www.tenouk.com
- ignore() member function skips over a designated number of characters (default is one character) or
terminates upon encountering a designated delimiter (default is EOF). For example:
cin.ignore(20,’\n’);
//gets and discards up to 20 characters or until
//newline character whichever comes first.
- putback() member function places the previous character obtained by a get() on an input stream
back onto that stream. For example:
char chs;
...
cin.putback(chs);
//put character back in the stream
- peek() member function returns the next character from an input stream, but does not remove the
character from the stream. For example:
char chs;
...
chs = cin.peek();
//peek at character
- Unformatted I/O performed with read() and write() member functions. They simply input or
output as raw byte.
- The read() member function extracts a given number of characters into an array and the write()
member function inserts n characters (nulls included). For example:
char texts[100];
...
cin.read(texts, 100);
//read 100 characters from input stream
//and don’t append ‘\0’
- Program example:
void main(void)
{
char buffer[SIZE];
www.tenouk.com
//the number of unformatted characters last extracted
cout<<endl;
system("pause");
}
Output:
- Program example:
void main(void)
{
int p;
www.tenouk.com
}
Output:
- Used to control the number of digits to the right of the decimal point.
- Use setprecision() or precision().
- precision 0 restores to the default precision of 6 decimal points.
void main(void)
{
double theroot = sqrt(11.55);
Output:
www.tenouk.com
18.4.3 Field Width
- Sets the field width and returns the previous width. If values processed are smaller than the field width,
fill characters are inserted as padding. Wider values will not be truncated.
- Use width() or setw(). For example:
- Program example:
void main(void)
{
int p = 6;
char string[20];
Output:
www.tenouk.com
18.4.4 Stream Format States
- Format state flag specify the kinds of formatting needed during the stream operations.
- Available member functions used to control the flag setting are: setf(), unsetf() and flags().
- flags() function must specify a value representing the settings of all the flags.
- The one argument, setf() function specifies one or more ORed flags and ORs them with the existing
flag setting to form a new format state.
- The setiosflags() parameterized stream manipulator performs the same functions as the setf.
- The resetiosflags() stream manipulator performs the same functions as the unsetf() member
function. For parameterized stream manipulators you need iomanip.h header file.
- Format state flags are defined as an enumeration in class ios. The list for some of the flags is shown
below:
- skipws flags indicates that >> should skip whitespace on an input stream. The default behavior of >>
is to skip whitespace. To change this, use the unsetf(ios::skipws). ws stream manipulator also
can be used for this purpose.
- ios::showpoint – this flag is set to force a floating point number to be output with its decimal
point and trailing zeroes. For example, floating point 88.0 will print 88 without showpoint set and
88.000000 (or many more 0s specified by current precision) with showpoint set.
www.tenouk.com
///Using showpoint
//controlling the trailing zeroes and floating points
#include <iostream.h>
#include <iomanip.h>
#include <stdlib.h>
void main(void)
{
cout<<"Before using the ios::showpoint flag\n"
<<"------------------------------------"<<endl;
cout<<"cout prints 88.88000 as: "<<88.88000
<<"\ncout prints 88.80000 as: "<<88.80000
<<"\ncout prints 88.00000 as: "<<88.00000
<<"\n\nAfter using the ios::showpoint flag\n"
<<"-----------------------------------"<<endl;
cout.setf(ios::showpoint);
cout<<"cout prints 88.88000 as: "<<88.88000
<<"\ncout prints 88.80000 as: "<<88.80000
<<"\ncout prints 88.00000 as: "<<88.00000<<endl;
system("pause");
}
Output:
18.4.6 Justification
void main(void)
{
long p = 123456789L;
//L - literal data type qualifier for long...
//F - float, UL unsigned integer...
cout<<"The default for 10 fields is right justified:\n"
<<setw(10)<<p
<<"\n\nUsing member function\n"
<<"---------------------\n"
www.tenouk.com
<<"\nUsing setf() to set ios::left:\n"<<setw(10);
cout.setf(ios::left,ios::adjustfield);
cout<<p<<"\nUsing unsetf() to restore the default:\n";
cout.unsetf(ios::left);
cout<<setw(10)<<p
<<"\n\nUsing parameterized stream manipulators\n"
<<"---------------------------------------\n"
<<"\nUse setiosflags() to set the ios::left:\n"
<<setw(10)<<setiosflags(ios::left)<<p
<<"\nUsing resetiosflags() to restore the default:\n"
<<setw(10)<<resetiosflags(ios::left)
<<p<<endl;
system("pause");
}
Output:
void main(void)
{
cout<<setiosflags(ios::internal | ios::showpos)
<<setw(12)<<12345<<endl;
system("pause");
}
Output:
18.4.7 Padding
- fill() – this member function specify the fill character to be used with adjusted field. If no value is
specified, spaces are used for padding. This function returns the prior padding character.
- setfill() – this manipulator also sets the padding character.
www.tenouk.com
#include <iostream.h>
#include <iomanip.h>
#include <stdlib.h>
void main(void)
{
long p = 30000;
cout<<p
<<" printed using the default pad character\n"
<<"for right and left justified and as hex\n"
<<"with internal justification.\n"
<<"--------------------------------------------\n";
cout.setf(ios::showbase);
cout<<setw(10)<<p<<endl;
cout.setf(ios::left,ios::adjustfield);
cout<<setw(10)<<p<<endl;
cout.setf(ios::internal,ios::adjustfield);
cout<<setw(10)<<hex<<p<<"\n\n";
Output:
- ios::basefield – includes the hex, oct and dec bits to specify that integers are to be treated as
hexadecimal, octal and decimal values respectively.
- If none of these bits is set, stream insertions default to decimal. Integers starting with 0 are treated as
octal values, starting with 0x or 0X are treated as hexadecimal values and all other integers are treated
as decimal values. So, set the showbase if you want to force the base of values to be output.
- Program example:
//using ios::showbase
#include <iostream.h>
#include <iomanip.h>
#include <stdlib.h>
void main(void)
{
www.tenouk.com
long p = 2000;
cout<<setiosflags(ios::showbase)
<<"Printing integers by their base:\n"
<<"--------------------------------\n"
<<"Decimal ---> "<<p<<'\n'
<<"Hexadecimal---> "<<hex<<p<<'\n'
<<"Octal ---> "<<oct<<p<<endl;
system("pause");
}
Output:
#include <iostream.h>
#include <stdlib.h>
void main(void)
{
cout<<"Declared variables\n"
<<"------------------\n"
<<"0.000654321"<<'\n'<<"9.8765e3"<<"\n\n";
cout<<"Default format:\n"
<<"---------------\n"
<<p<<'\t'<<q<<'\n'<<endl;
cout.setf(ios::scientific,ios::floatfield);
cout<<"Scientific format:\n"
<<"------------------\n"
<<p<<'\t'<<q<<'\n';
cout.unsetf(ios::scientific);
cout<<"\nDefault format after unsetf:\n"
<<"----------------------------\n"
<<p<<'\t'<<q<<endl;
cout.setf(ios::fixed,ios::floatfield);
cout<<"\nIn fixed format:\n"
<<"----------------\n"
<<p<<'\t'<<q<<endl;
www.tenouk.com
system("pause");
}
Output:
void main(void)
{
long p = 12345678;
cout<<setiosflags(ios::uppercase)
<<"Uppercase letters in scientific\n"
<<"notation-exponents and hexadecimal values:\n"
<<"------------------------------------------\n"
<<5.7654e12<<'\n'
<<hex<<p<<endl;
system("pause");
}
Output:
www.tenouk.com
//Demonstrating the flags() member function
//any format flags() not specified in the
//argument to flags() are reset.
#include <iostream.h>
#include <stdlib.h>
void main(void)
{
long p = 2000;
double q = 0.00124345;
cout.flags(OriginalFormat);
//restore the original format setting
cout<<"The value of the flags variable is: "
<<cout.flags()<<'\n'
<<"Print values in original format again:\n"
<<p<<'\t'<<q<<endl;
system("pause");
}
Output:
cin.eof()
- Will returns true if end-of-file has been encountered on cin and false otherwise.
- failbit(ios::failbit) is set for a stream when a format error occurs on the stream, but
character has not been lost. fail() member function determines if a stream operation has failed,
normally recoverable.
- badbit(ios::badbit) – is set for a stream when an error occurs that results in the loss of data.
bad() member function determines if a stream operation has failed, normally no recoverable.
www.tenouk.com
- goodbit(ios::goodbit) – is set for a stream if none of the bits eofbit(), failbit() or
badbit() are set for the stream. good() member function returns true if the bad(), fail() and
eof() functions would return false.
- rdstate() member function returns the error state of the stream. For example
cout.rdstate()
- Would return the state of the stream which could then be tested.
- clear() member function is normally used to restore a streams state to good() so that I/O may
proceed on the stream.
- Program example:
#include <iostream.h>
#include <stdlib.h>
void main(void)
{
int p;
Output:
www.tenouk.com
- Program example compiled using VC++/VC++ .Net.
#include <iostream>
using namespace std;
void main(void)
{
double p = 0.000654321, q = 9.8765e3;
cout<<"Declared variables\n"
<<"------------------\n"
<<"0.000654321"<<'\n'<<"9.8765e3"<<"\n\n";
cout<<"Default format:\n"
<<"---------------\n"
<<p<<'\t'<<q<<'\n'<<endl;
cout.setf(ios::scientific,ios::floatfield);
cout<<"Scientific format:\n"
<<"------------------\n"
<<p<<'\t'<<q<<'\n';
www.tenouk.com
cout.unsetf(ios::scientific);
cout<<"\nDefault format after unsetf:\n"
<<"----------------------------\n"
<<p<<'\t'<<q<<endl;
cout.setf(ios::fixed,ios::floatfield);
cout<<"\nIn fixed format:\n"
<<"----------------\n"
<<p<<'\t'<<q<<endl;
}
Output:
/////-padding.cpp-/////
//using fill() member function and setfill() manipulator
#include <iostream>
#include <iomanip>
using namespace std;
int main(void)
{
long p = 30000;
www.tenouk.com
[bodo@bakawali ~]$ ./padding
-----------------------------------------------o0o-----------------------------------------------
1. Check the best selling C/C++, Object Oriented and pattern analysis books at Amazon.com.
www.tenouk.com