Oops 3 Unit
Oops 3 Unit
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.
Input Stream: If the direction of flow of bytes is from the device(for example,
Keyboard) to the main memory then this process is called input.
Output Stream: If the direction of flow of bytes is opposite, i.e. from main
memory to device( display screen ) then this process is called output.
In C++ after the header files, we often use ‘using namespace std;‘. The reason
behind it is that all of the standard library definitions are inside the namespace std.
As the library functions are not defined at global scope, so in order to use them we
use namespace std. So, that we don’t need to write STD:: at every line (eg.
STD::cout etc.). To know more refer this article.
The two instances cout in C++ and cin in C++ of iostream class 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.
Standard output stream (cout): Usually the standard output device is the
display screen. The C++ cout statement is the instance of the ostream class. It
is used to produce output on the standard output device which is usually the
display screen. The data needed to be displayed on the screen is inserted in the
standard output stream (cout) using the insertion operator(<<).
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.
Un-buffered standard error stream (cerr): The C++ cerr is the standard
error stream that 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 it later.
The main difference between cerr and cout comes when you would like to
redirect output using “cout” that gets redirected to file if you use “cerr” the
error doesn’t get stored in file.(This is what un-buffered means ..It cant store
the message)
C++
#include <iostream>
int main()
{
cerr << "An error occurred";
return 0;
}
Output:
An error occurred
int main()
{
clog << "An error occurred";
return 0;
}
Output:
An error occurred
C++ helps you to format the I/O operations like determining the number of digits
to be displayed after the decimal point, specifying number base etc.
1. Manipulators with Arguments: Some of the manipulators are used with the
argument like setw (20), setfill (‘*’), and many more. These all are defined in
the header file. If we want to use these manipulators then we must include this
header file in our program. For Example, you can use following manipulators
to set minimum width and fill the empty space with any character you want:
std::cout << std::setw (6) << std::setfill (’*’);
Some important manipulators in <iomanip> are:
1. setw (val): It is used to set the field width in output operations.
2. setfill (c): It is used to fill the character ‘c’ on output stream.
3. setprecision (val): It sets val as the new value for the precision of
floating-point values.
4. setbase(val): It is used to set the numeric base value for numeric values.
5. setiosflags(flag): It is used to set the format flags specified by parameter
mask.
6. resetiosflags(m): It is used to reset the format flags specified by
parameter mask.
#include <iostream>
#include <iomanip>
main()
cout << "Hex Value =" << " " << hex << number << endl;
cout << "Octal Value=" << " " << oct << number << endl;
cout << "Setbase Value=" << " " << setbase(8) << number << endl;
cout << "Setbase Value=" << " " << setbase(16) << number << endl;
return 0;
Output
Hex Value = 64
Octal Value= 144
Setbase Value= 144
Setbase Value= 64
int main () {
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
Edit & run on cpp.sh
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.
Open a file
In order to open a file with a stream object we use its member function open:
All output operations are performed at the end of the file, appending the
ios::app
content to the current content of the file.
If the file is opened for output operations and it already existed, its
ios::trunc
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;
2 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:
ofstreamios::out
ifstream ios::in
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:
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:
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:
1 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:
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;
}
Edit & run on cpp.sh
Reading from a file can also be performed in the same way that we did with cin:
return 0;
}
Edit & run on cpp.sh
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.
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:
seekg ( position );
seekp ( position );
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:
The following example uses the member functions we have just seen to obtain the
size of a file:
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;
}
Edit & run on cpp.sh
Notice the type we have used for variables begin and end:
1 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.
Defined as fpos<mbstate_t>.
streamposios::pos_type It can be converted to/from streamoff and can be added or
subtracted values of these types.
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.