UNIT 4
Files and Streams
In C++ there are number of stream classes for defining various streams related with files and for doing input-output operations. All these classes are defined in the file iostream.h. Figure given below shows the hierarchy of these classes.
Heirarchy of Stream Classes in iostream.h
Facilities provided by these stream classes.
Example:
#include <iostream> using namespace std;
int main() { char x;
// used to scan a single char cin.get(x);
cout << x; } |
Input:
g
Output:
g
3. The ostream class: This class is responsible for handling output stream. It provides number of function for handling chars, strings and objects such as write, put etc..
Example:
#include <iostream> using namespace std;
int main() { char x;
// used to scan a single char cin.get(x);
// used to put a single char onto the screen. cout.put(x); } |
Input:
g
Output:
g
4. The iostream: This class is responsible for handling both input and output stream as both istream class and istream class is inherited into it. It provides function of both istream class and istream class for handling chars, strings and objects such as get, getline, read, ignore, putback, put, write etc..
Example:
#include <iostream> using namespace std;
int main() {
// this function display // ncount character from array cout.write("geeksforgeeks", 5); } |
Output:
geeks
5. istream_withassign class: This class is variant of istream that allows object assigment. The predefined object cin is an object of this class and thus may be reassigned at run time to a different istream object.
Example:To show that cin is object of istream class.
#include <iostream> using namespace std;
class demo { public: int dx, dy;
// operator overloading using friend function friend void operator>>(demo& d, istream& mycin) { // cin assigned to another object mycin mycin >> d.dx >> d.dy; } };
int main() { demo d; cout << "Enter two numbers dx and dy\n";
// calls operator >> function and // pass d and cin as reference d >> cin; // can also be written as operator >> (d, cin) ;
cout << "dx = " << d.dx << "\tdy = " << d.dy; } |
Input:
4 5
Output:
Enter two numbers dx and dy
4 5
dx = 4 dy = 5
6. ostream_withassign class: This class is variant of ostream that allows object assigment. The predefined objects cout, cerr, clog are objects of this class and thus may be reassigned at run time to a different ostream object.
Example:To show that cout is object of ostream class.
#include <iostream> using namespace std;
class demo { public: int dx, dy;
demo() { dx = 4; dy = 5; }
// operator overloading using friend function friend void operator<<(demo& d, ostream& mycout) { // cout assigned to another object mycout mycout << "Value of dx and dy are \n"; mycout << d.dx << " " << d.dy; } };
int main() { demo d; // default constructor is called
// calls operator << function and // pass d and cout as reference d << cout; // can also be written as operator << (d, cin) ; } |
Output:
Value of dx and dy are
4 5
We are using the iostream standard library; it provides cin and cout methods for reading from input and writing to output respectively.
To read and write from a file we are using the standard C++ library called fstream. Let us see the data types define in fstream library is:
Data Type | Description |
fstream | It is used to create files, write information to files, and read information from files. |
ifstream | It is used to read information from files. |
ofstream | It is used to create files and write information to the files. |
C++ FileStream example: writing to a file
Let's see the simple example of writing to a text file testout.txt using C++ FileStream programming.
Output:
The content of a text file testout.txt is set with the data:
Welcome to javaTpoint.
C++ Tutorial.
C++ FileStream example: reading from a file
Let's see the simple example of reading from a text file testout.txt using C++ FileStream programming.
Note: Before running the code a text file named as "testout.txt" is need to be created and the content of a text file is given below:
Welcome to javaTpoint.
C++ Tutorial.
Output:
Welcome to javaTpoint.
C++ Tutorial.
C++ Read and Write Example
Let's see the simple example of writing the data to a text file testout.txt and then reading the data from the file using C++ FileStream programming.
Output:
Writing to a text file:
Please Enter your name: Nakul Jain
Please Enter your age: 22
Reading from a text file: Nakul Jain
22
Stream classes in C++ are used to input and output operations on files and io devices. These classes have specific features and to handle input and output of the program.
The iostream.h library holds all the stream classes in the C++ programming language.
Let's see the hierarchy and learn about them,
Now, let’s learn about the classes of the iostream library.
ios class − This class is the base class for all stream classes. The streams can be input or output streams. This class defines members that are independent of how the templates of the class are defined.
istream Class − The istream class handles the input stream in c++ programming language. These input stream objects are used to read and interpret the input as a sequence of characters. The cin handles the input.
ostream class − The ostream class handles the output stream in c++ programming language. These output stream objects are used to write data as a sequence of characters on the screen. cout and puts handle the out streams in c++ programming language.
Example
OUT STREAMCOUT
#include <iostream>
using namespace std;
int main(){
cout<<"This output is printed on screen";
}
Output
This output is printed on screen
PUTS
#include <iostream>
using namespace std;
int main(){
puts("This output is printed using puts");
}
Output
This output is printed using puts
IN STREAMCIN
#include <iostream>
using namespace std;
int main(){
int no;
cout<<"Enter a number ";
cin>>no;
cout<<"Number entered using cin is "<
Output
Enter a number 3453
Number entered using cin is 3453
gets
#include <iostream>
using namespace std;
int main(){
char ch[10];
puts("Enter a character array");
gets(ch);
puts("The character array entered using gets is : ");
puts(ch);
}
Output
Enter a character array
thdgf
The character array entered using gets is :
thdgf
std::cerr is an object of class ostream that represents the standard error stream oriented to narrow characters (of type char). It corresponds to the C stream stderr. The standard error stream is a destination of characters determined by the environment. This destination may be shared by more than one standard object (such as cout or clog).
As an object of class ostream, characters can be written to it either as formatted data using the insertion operator (operator<<) or as unformatted data, using member functions such as write. The object is declared in the header <iostream> with external linkage and static duration: it lasts the entire duration of the program.
You can use this object to write to the screen. For example, if you want to write "Hello" to the screen, you'd write −
Example
#include<iostream>
int main() {
std::cerr << "Hello";
return 0;
}
Then save this program to hello.cpp file. Finally navigate to the saved location of this file in the terminal/cmd and compile it using −
$ g++ hello.cpp
Run it using −
$ ./a.out
Output
This will give the output −
Hello
C++ provides the following classes to perform output and input of characters to/from files:
These classes are derived directly or indirectly from the classes istream and ostream. We have already used objects whose types were these classes: cin is an object of class istream and cout is an object of class ostream. Therefore, we have already been using classes that are related to our file streams. And in fact, we can use our file streams the same way we are already used to use cin and cout, with the only difference that we have to associate these streams with physical files. Let's see an example:
1 | // basic file operations #include <iostream> #include <fstream> using namespace std;
int main () { ofstream myfile; myfile.open ("example.txt"); myfile << "Writing this to a file.\n"; myfile.close(); return 0; } | [file example.txt] Writing this to a file. |
|
This code creates a file called example.txt and inserts a sentence into it in the same way we are used to do with cout, but using the file stream myfile instead.
But let's go step by step:
Open a file
The first operation generally performed on an object of one of these classes is to associate it to a real file. This procedure is known as to open a file. An open file is represented within a program by a stream (i.e., an object of one of these classes; in the previous example, this was myfile) and any input or output operation performed on this stream object will be applied to the physical file associated to it.
In order to open a file with a stream object we use its member function open:
open (filename, mode);
Where filename is a string representing the name of the file to be opened, and mode is an optional parameter with a combination of the following flags:
ios::in | Open for input operations. |
ios::out | Open for output operations. |
ios::binary | Open in binary mode. |
ios::ate | Set the initial position at the end of the file. |
ios::app | All output operations are performed at the end of the file, appending the content to the current content of the file. |
ios::trunc | If the file is opened for output operations and it already existed, its previous content is deleted and replaced by the new one. |
All these flags can be combined using the bitwise operator OR (|). For example, if we want to open the file example.bin in binary mode to add data we could do it by the following call to member function open:
1 | ofstream myfile; myfile.open ("example.bin", ios::out | ios::app | ios::binary); |
|
Each of the open member functions of classes ofstream, ifstream and fstream has a default mode that is used if the file is opened without a second argument:
class | default mode parameter |
ofstream | ios::out |
ifstream | ios::in |
fstream | ios::in | ios::out |
For ifstream and ofstream classes, ios::in and ios::out are automatically and respectively assumed, even if a mode that does not include them is passed as second argument to the open member function (the flags are combined).
For fstream, the default value is only applied if the function is called without specifying any value for the mode parameter. If the function is called with any value in that parameter the default mode is overridden, not combined.
File streams opened in binary mode perform input and output operations independently of any format considerations. Non-binary files are known as text files, and some translations may occur due to formatting of some special characters (like newline and carriage return characters).
Since the first task that is performed on a file stream is generally to open a file, these three classes include a constructor that automatically calls the open member function and has the exact same parameters as this member. Therefore, we could also have declared the previous myfile object and conduct the same opening operation in our previous example by writing:
| ofstream myfile ("example.bin", ios::out | ios::app | ios::binary); |
|
Combining object construction and stream opening in a single statement. Both forms to open a file are valid and equivalent.
To check if a file stream was successful opening a file, you can do it by calling to member is_open. This member function returns a bool value of true in the case that indeed the stream object is associated with an open file, or false otherwise:
| if (myfile.is_open()) { /* ok, proceed with output */ } |
|
Closing a file
When we are finished with our input and output operations on a file we shall close it so that the operating system is notified and its resources become available again. For that, we call the stream's member function close. This member function takes flushes the associated buffers and closes the file:
| myfile.close(); |
|
Once this member function is called, the stream object can be re-used to open another file, and the file is available again to be opened by other processes.
In case that an object is destroyed while still associated with an open file, the destructor automatically calls the member function close.
Text files
Text file streams are those where the ios::binary flag is not included in their opening mode. These files are designed to store text and thus all values that are input or output from/to them can suffer some formatting transformations, which do not necessarily correspond to their literal binary value.
Writing operations on text files are performed in the same way we operated with cout:
1 | // writing on a text file #include <iostream> #include <fstream> using namespace std;
int main () { ofstream myfile ("example.txt"); if (myfile.is_open()) { myfile << "This is a line.\n"; myfile << "This is another line.\n"; myfile.close(); } else cout << "Unable to open file"; return 0; } | [file example.txt] This is a line. This is another line. |
|
Reading from a file can also be performed in the same way that we did with cin:
1 | // reading a text file #include <iostream> #include <fstream> #include <string> using namespace std;
int main () { string line; ifstream myfile ("example.txt"); if (myfile.is_open()) { while ( getline (myfile,line) ) { cout << line << '\n'; } myfile.close(); }
else cout << "Unable to open file";
return 0; } | This is a line. This is another line. |
|
This last example reads a text file and prints out its content on the screen. We have created a while loop that reads the file line by line, using getline. The value returned by getline is a reference to the stream object itself, which when evaluated as a boolean expression (as in this while-loop) is true if the stream is ready for more operations, and false if either the end of the file has been reached or if some other error occurred.
Checking state flags
The following member functions exist to check for specific states of a stream (all of them return a bool value):
bad()
Returns true if a reading or writing operation fails. For example, in the case that we try to write to a file that is not open for writing or if the device where we try to write has no space left.
fail()
Returns true in the same cases as bad(), but also in the case that a format error happens, like when an alphabetical character is extracted when we are trying to read an integer number.
eof()
Returns true if a file open for reading has reached the end.
good()
It is the most generic state flag: it returns false in the same cases in which calling any of the previous functions would return true. Note that good and bad are not exact opposites (good checks more state flags at once).
The member function clear() can be used to reset the state flags.
get and put stream positioning
All i/o streams objects keep internally -at least- one internal position:
ifstream, like istream, keeps an internal get position with the location of the element to be read in the next input operation.
ofstream, like ostream, keeps an internal put position with the location where the next element has to be written.
Finally, fstream, keeps both, the get and the put position, like iostream.
These internal stream positions point to the locations within the stream where the next reading or writing operation is performed. These positions can be observed and modified using the following member functions:
These two member functions with no parameters return a value of the member type streampos, which is a type representing the current get position (in the case of tellg) or the put position (in the case of tellp).
seekg() and seekp()These functions allow to change the location of the get and put positions. Both functions are overloaded with two different prototypes. The first form is:
seekg ( position );
seekp ( position );
Using this prototype, the stream pointer is changed to the absolute position position (counting from the beginning of the file). The type for this parameter is streampos, which is the same type as returned by functions tellg and tellp.
The other form for these functions is:
seekg ( offset, direction );
seekp ( offset, direction );
Using this prototype, the get or put position is set to an offset value relative to some specific point determined by the parameter direction. offset is of type streamoff. And direction is of type seekdir, which is an enumerated type that determines the point from where offset is counted from, and that can take any of the following values:
ios::beg | offset counted from the beginning of the stream |
ios::cur | offset counted from the current position |
ios::end | offset counted from the end of the stream |
The following example uses the member functions we have just seen to obtain the size of a file:
1 | // obtaining file size #include <iostream> #include <fstream> using namespace std;
int main () { streampos begin,end; ifstream myfile ("example.bin", ios::binary); begin = myfile.tellg(); myfile.seekg (0, ios::end); end = myfile.tellg(); myfile.close(); cout << "size is: " << (end-begin) << " bytes.\n"; return 0; } | size is: 40 bytes. |
|
Notice the type we have used for variables begin and end:
| streampos size; |
|
streampos is a specific type used for buffer and file positioning and is the type returned by file.tellg(). Values of this type can safely be subtracted from other values of the same type, and can also be converted to an integer type large enough to contain the size of the file.
These stream positioning functions use two particular types: streampos and streamoff. These types are also defined as member types of the stream class:
Type | Member type | Description |
streampos | ios::pos_type | Defined as fpos<mbstate_t>. |
streamoff | ios::off_type | It is an alias of one of the fundamental integral types (such as int or long long). |
Each of the member types above is an alias of its non-member equivalent (they are the exact same type). It does not matter which one is used. The member types are more generic, because they are the same on all stream objects (even on streams using exotic types of characters), but the non-member types are widely used in existing code for historical reasons.
Binary files
For binary files, reading and writing data with the extraction and insertion operators (<< and >>) and functions like getline is not efficient, since we do not need to format any data and data is likely not formatted in lines.
File streams include two member functions specifically designed to read and write binary data sequentially: write and read. The first one (write) is a member function of ostream (inherited by ofstream). And read is a member function of istream (inherited by ifstream). Objects of class fstream have both. Their prototypes are:
write ( memory_block, size );
read ( memory_block, size );
Where memory_block is of type char* (pointer to char), and represents the address of an array of bytes where the read data elements are stored or from where the data elements to be written are taken. The size parameter is an integer value that specifies the number of characters to be read or written from/to the memory block.
1 | // reading an entire binary file #include <iostream> #include <fstream> using namespace std;
int main () { streampos size; char * memblock;
ifstream file ("example.bin", ios::in|ios::binary|ios::ate); if (file.is_open()) { size = file.tellg(); memblock = new char [size]; file.seekg (0, ios::beg); file.read (memblock, size); file.close();
cout << "the entire file content is in memory";
delete[] memblock; } else cout << "Unable to open file"; return 0; } | the entire file content is in memory |
|
In this example, the entire file is read and stored in a memory block. Let's examine how this is done:
First, the file is open with the ios::ate flag, which means that the get pointer will be positioned at the end of the file. This way, when we call to member tellg(), we will directly obtain the size of the file.
Once we have obtained the size of the file, we request the allocation of a memory block large enough to hold the entire file:
| memblock = new char[size]; |
|
Right after that, we proceed to set the get position at the beginning of the file (remember that we opened the file with this pointer at the end), then we read the entire file, and finally close it:
1 | file.seekg (0, ios::beg); file.read (memblock, size); file.close(); |
|
At this point we could operate with the data obtained from the file. But our program simply announces that the content of the file is in memory and then finishes.
Buffers and Synchronization
When we operate with file streams, these are associated to an internal buffer object of type streambuf. This buffer object may represent a memory block that acts as an intermediary between the stream and the physical file. For example, with an ofstream, each time the member function put (which writes a single character) is called, the character may be inserted in this intermediate buffer instead of being written directly to the physical file with which the stream is associated.
The operating system may also define other layers of buffering for reading and writing to files.
When the buffer is flushed, all the data contained in it is written to the physical medium (if it is an output stream). This process is called synchronization and takes place under any of the following circumstances:
Read Mode
Fig.: Get pointer in read mode
Write mode
Fig.: Put pointer in write mode
Append Mode
Fig. : Get pointer in append mode
In append mode put pointer is set at the end of file.
Program
Program to append a file.
#include<iostream>
using namespace std;
#include<conio.h>
int main()
{
clrscr();
{
ofstream fout;
char X[50];
fout.open(“Demo”, ios::out);
cout<<”Enter text”<<endl;
cin.getline(X,50);
fout<<X;
fout.close();
fout.open(“Demo”, ios::app);
cout<<”\n Enter text again”<<endl;
cin.getline(X,50);
fout<<X;
fout.close();
ifstream fin;
fin.open(“Demo”, ios::in);
cout<<”/n Contents of file”;
while(fin.eof==0)
{
fin>>data;
cout<<data;
}
return 0;
}
Function | Meaning |
int bad() | Returns true (non zero value) if invalid operation or unrecoverable error is encountered and false(zero) for recoverable error. |
int eof() | Returns true if end of file is encountered otherwise false. |
int good() | Returns true if no error is encountered otherwise false. |
fail() | Returns true if input/output operation has failed. |
clear() | Resets the error state so that further operations can be attempted. |
ifstream fin;
fin.open("master", ios::in);
while(!fin.fail())
{
: // process the file
}
if(fin.eof())
{
: // terminate the program
}
else if(fin.bad())
{
: // report fatal error
}
else
{
fin.clear(); // clear error-state flags
:
}
ifstream fin(“demo.txt”);
if(!fin)
cout<<”File not found”;
ifstream fin(“demo.txt”);
while(!fin.eof())
{
Read data;
Write data;
}
So far, we have been using the iostream standard library, which provides cin and cout methods for reading from standard input and writing to standard output respectively.
This tutorial will teach you how to read and write from a file. This requires another standard C++ library called fstream, which defines three new data types −
Sr.No | Data Type & Description |
1 | Ofstream This data type represents the output file stream and is used to create files and to write information to files. |
2 | Ifstream This data type represents the input file stream and is used to read information from files. |
3 | Fstream This data type represents the file stream generally, and has the capabilities of both ofstream and ifstream which means it can create files, write information to files, and read information from files. |
To perform file processing in C++, header files <iostream> and <fstream> must be included in your C++ source file.
Opening a File
A file must be opened before you can read from it or write to it. Either ofstream or fstream object may be used to open a file for writing. And ifstream object is used to open a file for reading purpose only.
Following is the standard syntax for open() function, which is a member of fstream, ifstream, and ofstream objects.
void open(const char *filename, ios::openmode mode);
Here, the first argument specifies the name and location of the file to be opened and the second argument of the open() member function defines the mode in which the file should be opened.
Sr.No | Mode Flag & Description |
1 | ios::app Append mode. All output to that file to be appended to the end. |
2 | ios::ate Open a file for output and move the read/write control to the end of the file. |
3 | ios::in Open a file for reading. |
4 | ios::out Open a file for writing. |
5 | ios::trunc If the file already exists, its contents will be truncated before opening the file. |
You can combine two or more of these values by ORing them together. For example if you want to open a file in write mode and want to truncate it in case that already exists, following will be the syntax −
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );
Similar way, you can open a file for reading and writing purpose as follows −
fstream afile;
afile.open("file.dat", ios::out | ios::in );
Closing a File
When a C++ program terminates it automatically flushes all the streams, release all the allocated memory and close all the opened files. But it is always a good practice that a programmer should close all the opened files before program termination.
Following is the standard syntax for close() function, which is a member of fstream, ifstream, and ofstream objects.
void close();
Writing to a File
While doing C++ programming, you write information to a file from your program using the stream insertion operator (<<) just as you use that operator to output information to the screen. The only difference is that you use an ofstream or fstream object instead of the cout object.
Reading from a File
You read information from a file into your program using the stream extraction operator (>>) just as you use that operator to input information from the keyboard. The only difference is that you use an ifstream or fstream object instead of the cin object.
Read and Write Example
Following is the C++ program which opens a file in reading and writing mode. After writing information entered by the user to a file named afile.dat, the program reads information from the file and outputs it onto the screen −
#include <fstream>
#include <iostream>
using namespace std;
int main () {
char data[100];
// open a file in write mode.
ofstream outfile;
outfile.open("afile.dat");
cout << "Writing to the file" << endl;
cout << "Enter your name: ";
cin.getline(data, 100);
// write inputted data into the file.
outfile << data << endl;
cout << "Enter your age: ";
cin >> data;
cin.ignore();
// again write inputted data into the file.
outfile << data << endl;
// close the opened file.
outfile.close();
// open a file in read mode.
ifstream infile;
infile.open("afile.dat");
cout << "Reading from the file" << endl;
infile >> data;
// write the data at the screen.
cout << data << endl;
// again read the data from the file and display it.
infile >> data;
cout << data << endl;
// close the opened file.
infile.close();
return 0;
}
When the above code is compiled and executed, it produces the following sample input and output −
$./a.out
Writing to the file
Enter your name: Zara
Enter your age: 9
Reading from the file
Zara
9
Above examples make use of additional functions from cin object, like getline() function to read the line from outside and ignore() function to ignore the extra characters left by previous read statement.
File Position Pointers
Both istream and ostream provide member functions for repositioning the file-position pointer. These member functions are seekg ("seek get") for istream and seekp ("seek put") for ostream.
The argument to seekg and seekp normally is a long integer. A second argument can be specified to indicate the seek direction. The seek direction can be ios::beg (the default) for positioning relative to the beginning of a stream, ios::cur for positioning relative to the current position in a stream or ios::end for positioning relative to the end of a stream.
The file-position pointer is an integer value that specifies the location in the file as a number of bytes from the file's starting location. Some examples of positioning the "get" file-position pointer are −
// position to the nth byte of fileObject (assumes ios::beg)
fileObject.seekg( n );
// position n bytes forward in fileObject
fileObject.seekg( n, ios::cur );
// position n bytes back from end of fileObject
fileObject.seekg( n, ios::end );
// position at end of fileObject
fileObject.seekg( 0, ios::end );
C++ is able to input and output the built-in data types using the stream extraction operator >> and the stream insertion operator <<. The stream insertion and stream extraction operators also can be overloaded to perform input and output for user-defined types like an object.
Here, it is important to make operator overloading function a friend of the class because it would be called without creating an object.
Following example explains how extraction operator >> and insertion operator <<.
Example Code
#include <iostream>
using namespace std;
class Distance {
private:
int feet; // 0 to infinite
int inches; // 0 to 12
public:
// required constructors
Distance() {
feet = 0;
inches = 0;
}
Distance(int f, int i) {
feet = f;
inches = i;
}
friend ostream &operator<<( ostream &output, const Distance &D ) {
output << "F : " << D.feet << " I : " << D.inches;
return output;
}
friend istream &operator>>( istream &input, Distance &D ) {
input >> D.feet >> D.inches;
return input;
}
};
int main() {
Distance D1(11, 10), D2(5, 11), D3;
cout << "Enter the value of object : " << endl;
cin >> D3;
cout << "First Distance : " << D1 << endl;
cout << "Second Distance :" << D2 << endl;
cout << "Third Distance :" << D3 << endl;
return 0;
}
Output
$./a.out
Enter the value of object :
70
10
First Distance : F : 11 I : 10
Second Distance :F : 5 I : 11
Third Distance :F : 70 I : 10
C++, like its ancestor C, has no inherent I/O facilities, and like C relies on standard libraries for its I/O. In addition to the C functions printf and scanf, C++ has two object-based streams namely cout and cin.
C & C++ streams are nearly but not quite the same. C streams are buffered I/O streams that are accessed via function calls, whereas C++ streams are objects that interface to buffered I/O streams. A C stream is not extensible, you cannot add your own '%' formatting codes. The hierarchy of classes that form the C++ streams are extensible by the programmer.
A user can, when defining an object, define how a stream will output or input the information from or into the object. This is a big aid to standardizing the I/O of objects within a suite of programs.
Console Output
The C++ stream that outputs information to the screen is called cout (Console OUTput). This object uses a multiply-overloaded left-bit-shift operator ( << ) to feed information to the screen. The left-bit-shift operator in the context of streams is known as the inserter operator because it inserts information into the stream.
cout << "This is a simple string" ;
The standard C string codes such as \n can still be used, however, it is preferred to use 'endl' (endline) to force end of line (equivalent of \n & flush).
cout << "This is line 1" << endl
<< "This is line 2 with a value of " << myvalue << endl ;
Notice that the variable myvalue does not need any of the usual '%' formatting codes used by C. This is achieved by the multiple overloading of the inserter operator for each of the fundamental data types, i.e. one each for ints, longs, floats, chars and char* types. The programmer can extend the overloading of the inserter operator to control the formatted output of their own objects.
Console Input
The C++ stream that extracts information from the input stream is called cin (Console INput). This object uses the multiply-overloaded right-bit-shift operator ( >> ) to feed information from the input stream into variables.
The right-bit-shift operator in the context of streams is known as the extractor operator, for obvious reasons.
cin >> myint >> mystring >> mylongfloat;
Like cout, cin does not require '%' string formatting codes as in the case of the scanf function, 'cin' also only requires the name of the variable and not a pointer to the variable as in the case of scanf. Again this is achieved by multiply overloading the extraction operator.
Manipulators
The I/O streams can utilize a series of manipulators to change the characteristics of the output. We have already seen 'endl'. Others include 'hex', 'dec' and 'oct' for base conversion, manipulators for whitespace removal, 'ends' to insert a string terminator character into the stream and flush it. (mainly used in strstream, a similar in function to sprintf), 'setprecision' and 'setw' set the number of decimal places and the width of the output of the next data item respectively. There are also a set of flags, called 'ios' flags (Input-Output-Stream flags). These are a series of bit flags used for controlling and detecting errors on the streams. These will be covered in more detail by later articles on streams.
Mixing Old and New
Although it is possible to use both C++ streams and C streams in the same program, it would not be wise to do so. Output to the screen is buffered, so if printf and cout are both outputting to the screen, only when their buffers are flushed does the actual text hit the screen. Although experiments with Borland C++ version 3.1 seem able to handle mixed C and C++ streams without any problems. Borland does provide a syncronisa-tion member function in the ios class called 'sync_with_stdio'.
Examples of stream Manipulators
As mentioned previously, the output and input streams can have modifiers applied to the way in which the stream behaves.
float my_float = 22.9756;
cout << setiosflags(ios::fixed | ios: :showpoint)
<< setprecision(2)
<< my_float
<< endl;
Output would be 22.98 - note the automatic rounding caused by set precision, without this manipulator the result would have been 22.97559 (due to inaccuracies of floating point numbers)
int k = 0;
cin >> hex >> k;
cout << endl
<< "The value entered is " << k;
If the user entered 10 the printed number would be 16. (i.e. 10 hex == 16 decimal).
A complete list of these manipulators can be found in the 'Borland user guide' in the section 'Using C++ streams'.
In-Memory Formatting
In C++, sprintf is replaced by the ostrstream class. It is easier to use than sprintf and follows the same formatting rules as cout, except that the target is not cout but the object of type strstream or ostrstream.
Automatic Memory Allocation An object of type 'ostrstream' uses a dynamically allocated buffer. This is handy if the size of the resulting output is unknown.
ostrstream buffer;
const float PI = 3.14159265;
const float r = 10.5;
buffer << "The area of the circle of radius " << r
<< " = " << PI*r*r << ends;
cout << buffer.str() << endl;
The resulting output will be The area of circle of radius 10.5 = 346.360596' Note: The 'ends' stream manipulator (end string) is the equivalent of '\0' the string terminator.
Manual Memory Allocation
The 'ostrstream' class can be tied to a specified area of memory. As a consequence a fixed size buffer must be allocated.
const int Length = 100;
char memstring[Length];
ostrstream storage(memstring, Length);
const float PI = 3.14159265;
const float r = 10.5;
storage << "The area of the circle of radius " << r
<< " = " << PI*r*r << ends;
cout << storage.str() << endl;
Obviously the string memstring could by output directly:
cout << memstring << endl ;
Problems with 'ostream'
The disadvantage of the dynamically allocated buffer is that to print it you must use the str() member function. This has the side effect that the stream is 'frozen' and is not deleted from memory when the object goes out of scope unless explicitly 'unfrozen' with the srreambuf::freeze(0) member function. The reasons behind this are beyond the scope of this article and will be covered in a later issue.
From-Memory Reading
To read from a variable is relatively straight-forward. An istream object is set up and used in a similar manner to cin. The only awkward bit is reading in strings. For this you have to remember to remove whitespace and to use the get() or getline() member functions of the stream to copy the string to the target variable.
char memory_info[] = "100 200 22.995 hello fred";
int 11, i2; float f1;
char sl[10], s2[10] ;
istrstream stringstream (memory_info, sizeof(memory_info));
stringstream >> i1 >> i2 >> f1;
stringstream >> ws;
stringstream.get(sl,10,' ');
stringstream >> ws;
stringstream.get(s2,10,' ');
cout << "i1 = " << il << endl
<< "i2 = " << i2 << endl
<< "f1 = " << f1 << endl
<< "s1 = " << s1 << endl
<< "s2 = " << s2 << endl;
A Superior Console I/O
The streams mentioned this far have all been streams defined in the proposed ANSI standards. In order to be useful on DOS systems, the Turbo/Borland C++ (version 3.0+) has an additional stream which is the equivalent of the conio (direct console) functions. This stream enables colour changing of text, cursor positioning, highlighting etc.
This stream is called constream and has been derived from the ostream stream. It can be limited to write only to certain areas of the screen. The beauty of such streams is that colour, cursor position etc remains constant for one instantiation of the constream. If output to another instantiation of constream occurrs no modification to the characteristics of the first constream occurs. Examine and compile the programs postest.cpp and constr.cpp on the companion disk to see what I mean.
constream console;
console << setxy(10,10)
<< "Hello world "
<< highvideo
<< "Im highlighted "
<< lowvideo
<< "and Im dim "
<< normvideo
<< "and Im norman";
It is possible to pass some values from the command line to your C programs when they are executed. These values are called command line arguments and many times they are important for your program especially when you want to control your program from outside instead of hard coding those values inside the code.
The command line arguments are handled using main() function arguments where argc refers to the number of arguments passed, and argv[] is a pointer array which points to each argument passed to the program. Following is a simple example which checks if there is any argument supplied from the command line and take action accordingly −
Example
#include <stdio.h>
int main( int argc, char *argv[] ) {
if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n");
}
}
Output
$./a.out testing
The argument supplied is testing
Output
$./a.out testing1 testing2
Too many arguments supplied.
Output
$./a.out
One argument expected
It should be noted that argv[0] holds the name of the program itself and argv[1] is a pointer to the first command line argument supplied, and *argv[n] is the last argument. If no arguments are supplied, argc will be one, and if you pass one argument then argc is set at 2.
You pass all the command line arguments separated by a space, but if argument itself has a space then you can pass such arguments by putting them inside double quotes "" or single quotes ''. Let us re-write above example once again where we will print program name and we also pass a command line argument by putting inside double quotes −
Example
#include <stdio.h>
int main( int argc, char *argv[] ) {
printf("Program name %s\n", argv[0]);
if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n");
}
}
Output
$./a.out "testing1 testing2"
Progranm name ./a.out
The argument supplied is testing1 testing2
C++ comes with libraries that provide us with many ways for performing input and output. In C++ input and output are performed in the form of a sequence of bytes or more commonly known as streams.
Header files available in C++ for Input/Output operations are:
The two keywords cout in C++ and cin in C++ are used very often for printing outputs and taking inputs respectively. These two are the most basic methods of taking input and printing output in C++. To use cin and cout in C++ one must include the header file iostream in the program.
This article mainly discusses the objects defined in the header file iostream like the cin and cout.
#include <iostream>
using namespace std;
int main() { char sample[] = "GeeksforGeeks";
cout << sample << " - A computer science portal for geeks";
return 0; } |
Output:
GeeksforGeeks - A computer science portal for geeks
In the above program the insertion operator(<<) inserts the value of the string variable sample followed by the string “A computer science portal for geeks” in the standard output stream cout which is then displayed on screen.
II. standard input stream (cin): Usually the input device in a computer is the keyboard. C++ cin statement is the instance of the class istream and is used to read input from the standard input device which is usually a keyboard.
The extraction operator(>>) is used along with the object cin for reading inputs. The extraction operator extracts the data from the object cin which is entered using the keyboard.
#include <iostream> using namespace std;
int main() { int age;
cout << "Enter your age:"; cin >> age; cout << "\nYour age is: " << age;
return 0; } |
Input :
18
Output:
Enter your age:
Your age is: 18
The above program asks the user to input the age. The object cin is connected to the input device. The age entered by the user is extracted from cin using the extraction operator(>>) and the extracted data is then stored in the variable age present on the right side of the extraction operator.
III. Un-buffered standard error stream (cerr): The C++ cerr is the standard error stream which is used to output the errors. This is also an instance of the iostream class. As cerr in C++ is un-buffered so it is used when one needs to display the error message immediately. It does not have any buffer to store the error message and display later.
#include <iostream>
using namespace std;
int main() { cerr << "An error occured"; return 0; } |
Output:
An error occurred
IV. buffered standard error stream (clog): This is also an instance of iostream class and used to display errors but unlike cerr the error is first inserted into a buffer and is stored in the buffer until it is not fully filled. The error message will be displayed on the screen too.
#include <iostream>
using namespace std;
int main() { clog << "An error occurred";
return 0; } |
Output:
An error occurred
References:
1. Herbert Schildt, ―C++ The complete reference‖, Eighth Edition, McGraw Hill Professional, 2011, ISBN:978-00-72226805
2. Matt Weisfeld, ―The Object-Oriented Thought Process, Third Edition Pearson ISBN-13:075- 2063330166
3. Cox Brad, Andrew J. Novobilski, ―Object –Oriented Programming: An EvolutionaryApproach‖, Second Edition, Addison–Wesley, ISBN:13:978-020-1548341
4. Deitel, “C++ How to Program”, 4th Edition, Pearson Education, ISBN:81-297-0276-2