< C++ Virtual Function 2 | Main | C++ Formatted I/O 2 >| Site Index | Download >


 

 

 

 

MODULE 18

C++ STREAM FORMATTED I/O 1

--------------------------------------------------------------------------------------------

MODULE 5: C FORMATTED I/O

 

 

 

 

 

 

 

My Training Period: xx  hours

 

The source code for this tutorial is available in C++ Formatted I/O source codes.

 

The C++ formatted I/O programming skills:

 

  • To understand and use various member functions for C++ formatted I/O.

  • To understand and use various stream manipulators for C++ formatted I/O.

 

18.1  iostream Library

  • In C Formatted I/O 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 C++ Data Encapsulation until C++ Polymorphism, 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 C Formatted I/O.

  • The header files used for formatted I/O in C++ are:

Header file

Brief description

<iostream>

Provide basic information required for all stream I/O operation such as cin, cout, cerr and clog correspond to standard input stream, standard output stream, and standard unbuffered and buffered error streams respectively.

<iomanip>

Contains information useful for performing formatted I/O with parameterized stream manipulation.

<fstream>

Contains information for user controlled file processing operations.

<strstream>

Contains information for performing in-memory formatting or in-core formatting.  This resembles file processing, but the I/O operation is performed to and from character arrays rather than files.

<stdiostrem>

Contains information for program that mixes the C and C++ styles of I/O.

 

Table 18.1:  iostream library

  • 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 Namespaces for more information.

  • The iostream class hierarchy is shown below.  From the base class ios, we have a derived class:

Class

Brief description

istream

Class for stream input operation.

ostream

Class for stream output operation.

 

Table 18.2:  ios derived classes

  • So, iostream support both stream input and output.  The class hierarchy is shown below.

 

C++ ios class hierarchy

18.2  Left and Right Shift Operators

Operators

Brief description

cin

Object of istream class, connected to the standard input device, normally the keyboard.

cout

Object of ostream class, connected to standard output device, normally the display/screen.

cerr

Object of the ostream class connected to standard error device.  This is unbuffered output, so each insertion to cerr causes its output to appear immediately.

clog

Same as cerr but outputs to clog are buffered.

 

Table 18.3:  iostream operators

Class

Brief description

ifstream

To perform file input operations.

ofstream

For file output operation.

fstream

For file input/output operations.

 

Table 18.4:  File input/output classes

// string output using <<

#include <iostream>

using namespace std;

 

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

}

 

Output:

 

C++ stream output program example

 

// concatenating <<

#include <iostream>

using namespace std;

 

void main(void)

{

int p = 3, q = 10;

 

cout << "Concatenating using << operator.\n"

     <<"--------------------------------"<<endl;

cout << "70 minus 20 is "<<(70 - 20)<<endl;

cout << "55 plus 4 is "<<(55 + 4)<<endl;

cout <<p<<" + "<<q<<" = "<<(p+q)<<endl;

}

 

Output:

 

C++ stream output concat program example

#include <iostream.h>

using namespace std;

 

void main(void)

{

int p, q, r;

 

cout << "Enter 3 integers separated by space: \n";

cin>>p>>q>>r;

// the >> operator skips whitespace characters such as tabs,

// blank space and newline.  When eof is encountered, zero (false) is returned.

cout<<"Sum of the "<<p<<","<<q<<" and "<<r<<" is = "<<(p+q+r)<<endl;

}

 

Output:

 

C++ stream input program output example

 

 

18.3  get() and getline() Member Functions of Stream Input

  • 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();

  1. 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);

  1. 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.

  1. 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.

// end of file controls depend on system

// Ctrl-z followed by return key - IBM PC, Ctrl-d - UNIX and MAC

#include <iostream>

using namespace std;

 

void main(void)

{

char p;

 

cout <<"Using member functions get(), eof() and put()\n"

     <<"---------------------------------------------"<<endl;

cout<<"Before any input, cin.eof() is "<<cin.eof()<<endl;

cout<<"Enter a line of texts followed by end of file control: "<<endl;

 

while((p = cin.get()) !=EOF)

    cout.put(p);

cout<<"\nAfter some text input, cin.eof() is "<<cin.eof()<<endl;

}

 

Output:

 

C++ stream formatted IO, get(), eof(), put() program example

 

// another get() version

#include <iostream>

using namespace std;

 

const int SIZE = 100;

 

void main(void)

{

char bufferOne[SIZE], bufferTwo[SIZE];

 

cout <<"Enter a line of text:"<<endl;

cin>>bufferOne;

// store the string in array bufferOne

// just the first word in the array string, then the

// first whitespace encountered

cout<<"\nThe line of text read by cin>> was:"<<endl;

cout<<bufferOne<<endl;

cin.get(bufferTwo, SIZE);

// the rest of the string

cout<<"The line of text read by cin.get(bufferTwo,SIZE) was:"<<endl;

cout<<bufferTwo<<endl;

}

 

Output:

 

C++ stream formatted I/O get() program example

 

// getline() example

#include <iostream>

using namespace std;

 

const SIZE = 100;

 

void main(void)

{

char buffer[SIZE];

 

cout<<"Read by cin.getline(buffer, SIZE)\n"

    <<"--------------------------------\n"<<"Enter a line of text:"<<endl;

cin.getline(buffer, SIZE);

cout<<"The line of text entered is: "<<endl;

cout<<buffer<<endl;

}

 

Output:

 

C++ stream formatted I/O getline() program example

cin.ignore();        // gets and discards 1 character.

 

cin.ignore(5);       // gets and discards 5 characters.

 

cin.ignore(20,’\n’);

// gets and discards up to 20 characters or until

// newline character whichever comes first.

char chs;

...

cin.putback(chs);

// put character back in the stream

char chs;

...

chs = cin.peek();

// peek at character

char texts[100];

...

cin.read(texts, 100);

// read 100 characters from input stream and don’t append ‘\0’

// using read(), write() and gcount() member functions

#include <iostream>

using namespace std;

 

const int SIZE = 100;

 

void main(void)

{

char buffer[SIZE];

 

cout<<"Enter a line of text:"<<endl;

cin.read(buffer,45);

cout<<"The line of text entered was: "<<endl;

cout.write(buffer, cin.gcount());

// the gcount() member function returns

// the number of unformatted characters last extracted

cout<<endl;

}

 

Output:

 

C++ stream formatted I/O read write gcount() program example

 

 

18.4  Stream Manipulators

  1. Setting field width.

  2. Precision.

  3. Unsetting format flags.

  4. Flushing stream.

  5. Inserting newline in the output stream and flushing the stream.

  6. Inserting the null character in the output stream.

  7. Skipping whitespace.

  8. Setting the fill character in field.

18.4.1  Stream Base

Operator/function

Brief description

hex

To set the base to hexadecimal, base 16.

oct

To set the base to octal, base 8.

dec

To reset the stream to decimal.

setbase()

Changing the base of the stream, taking one integer argument of 10, 8 or 16 for decimal, base 8 or base 16 respectively.  setbase() is parameterized stream manipulator by taking argument, we have to include iomanip header file.

 

Table 18.5:  Stream base operator and function.

// using hex, oct, dec and setbase stream manipulator

#include <iostream>

using namespace std;

#include <iomanip>

 

void main(void)

{

int p;

 

cout<<"Enter a decimal number:"<<endl;

cin>>p;

cout<<p<< " in hexadecimal is: "

<<hex<<p<<'\n'

<<dec<<p<<" in octal is: "

<<oct<<p<<'\n'

<<setbase(10) <<p<<" in decimal is: "

<<p<<endl;

cout<<endl;

}

 

Output:

 

 

 

 

 

 

 

 

 

 

 

C++ stream formatted I/O setbase hex oct dec

 

18.4.2  Floating-point Precision

// using precision and setprecision

#include <iostream>

using namespace std;

#include <iomanip>

// using C++ wrappers to access C function

#include <cmath>

 

void main(void)

{

double theroot = sqrt(11.55);

 

cout<<"Square root of 11.55 with various"<<endl;

cout<<"           precisions"<<endl;

cout<<"---------------------------------"<<endl;

cout<<"Using 'precision':"<<endl;

for(int poinplace=0; poinplace<=8; poinplace++)

{

cout.precision(poinplace);

cout<<theroot<<endl;

}

cout<<"\nUsing 'setprecision':"<<endl;

for(int poinplace=0; poinplace<=8; poinplace++)

cout<<setprecision(poinplace)<<theroot<<endl;

}

 

Output:

 

C++ stream formatted I/O precision setprecision

 

18.4.3  Field Width

cout.width(6);  // field is 6 position wide

// using width member function

#include <iostream>

using namespace std;

 

void main(void)

{

       int p = 6;

       char string[20];

 

       cout<<"Using field width with setw() or width()"<<endl;

       cout<<"----------------------------------------"<<endl;

       cout<<"Enter a line of text:"<<endl;

       cin.width(7);

       while (cin>>string)

       {

              cout.width(p++);

              cout<<string<<endl;

              cin.width(7);

              // use ctrl-z followed by return key or ctrl-d to exit

       }

}

 

Output:

 

C++ stream formatted I/O setw width

 

tenouk C++ formatted I/O tutorial

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Further C++ formatted I/O reading:

 

  1. The source code for this tutorial is available in C++ Formatted I/O source codes.

  2. Visual C++ .NET programming tutorials.

  3. Check the best selling C / C++, Object Oriented and pattern analysis books at Amazon.com.

 

 

 

 

 

 

|< C++ Virtual Function 2 | Main | C++ Formatted I/O 2 >| Site Index | Download |


C++ Stream Formatted Input/Output:  Part 1 | Part 2