--------------------------------------------------------------------------------------------
| 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:
18.1 iostream Library
|
We have used these operators in most of the previous tutorials 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:
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 |
For file processing C++ uses (will be discussed in another Module) the following classes:
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 |
Stream output program example:
// 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
}
// 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;
}
Stream input 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;
}
18.3 get() and getline() Member Functions of Stream Input
cin.get();
char ch; ... cin.get(ch);
|
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.
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.
A program examples:
// 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;
}
// 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;
}
// 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;
}
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(); // 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.
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:
// 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;
}
Used to perform formatting, such as:
Setting field width.
Precision.
Unsetting format flags.
Flushing stream.
Inserting newline in the output stream and flushing the stream.
Inserting the null character in the output stream.
Skipping whitespace.
Setting the fill character in field.
For stream base we have:
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. |
Program example:
// 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;
}
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.
// 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;
}
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:
cout.width(6); // field is 6 position wide
A program example:
// 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
}
}
tenouk C++ formatted I/O tutorial
The source code for this tutorial is available in C++ Formatted I/O source codes.
Check the best selling C / C++, Object Oriented and pattern analysis books at Amazon.com.