0% found this document useful (0 votes)
8 views

Oops 3 Unit

Uploaded by

Pavan 0205
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Oops 3 Unit

Uploaded by

Pavan 0205
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Basic Input / Output in C++



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.

Header files available in C++ for Input/Output operations are:


1. iostream: iostream stands for standard input-output stream. This header file
contains definitions of objects like cin, cout, cerr, etc.
2. iomanip: iomanip stands for input-output manipulators. The methods declared
in these files are used for manipulating streams. This file contains definitions of
setw, setprecision, etc.
3. fstream: This header file mainly describes the file stream. This header file is
used to handle the data being read from a file as input or data being written into
the file as 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>

using namespace std;

int main()
{
cerr << "An error occurred";
return 0;
}
Output:
An error occurred

 buffered standard error stream (clog): This is also an instance of ostream


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. or the buffer is not
explicitly flushed (using flush()). The error message will be displayed on the
screen too.
C++
#include <iostream>

using namespace std;

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.

There are two ways to do so:


1. Using the ios class or various ios member functions.
2. Using manipulators(special functions)
I. Formatting using the ios members:
The stream has the format flags that control the way of formatting it means
Using this setf function, we can set the flags, which allow us to display a
value in a particular format. The ios class declares a bitmask enumeration
called fmtflags in which the values(showbase, showpoint, oct, hex etc) are
defined. These values are used to set or clear the format flags.
Few standard ios class functions are:
1. width(): The width method is used to set the required field width. The
output will be displayed in the given width
2. precision(): The precision method is used to set the number of the
decimal point to a float value
3. fill(): The fill method is used to set a character to fill in the blank space of
a field
4. setf(): The setf method is used to set various flags for formatting output
5. unsetf(): The unsetf method is used To remove the flag setting

Manipulators in C++ with Examples


Manipulators are helping functions that can modify the input/output stream. It
does not mean that we change the value of a variable, it only modifies the I/O
stream using insertion (<<) and extraction (>>) operators.
 Manipulators are special functions that can be included in the I/O statement to
alter the format parameters of a stream.
 Manipulators are operators that are used to format the data display.
 To access manipulators, the file iomanip.h should be included in the program.

Types of Manipulators There are various types of manipulators:

1. Manipulators without arguments: The most important manipulators defined


by the IOStream library are provided below.
 endl: It is defined in ostream. It is used to enter a new line and after entering
a new line it flushes (i.e. it forces all the output written on the screen or in
the file) the output stream.
 ws: It is defined in istream and is used to ignore the whitespaces in the
string sequence.
 ends: It is also defined in ostream and it inserts a null character into the
output stream. It typically works with std::ostrstream, when the associated
output buffer needs to be null-terminated to be processed as a C string.
 flush: It is also defined in ostream and it flushes the output stream, i.e. it
forces all the output written on the screen or in the file. Without flush, the
output would be the same, but may not appear in real-time.

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.

 Some important manipulators in <ios> are:


1. fixed: It uses decimal notation for floating-point values.
2. scientific: It uses scientific floating-point notation.
3. hex: Read and write hexadecimal values for integers and it works same
as the setbase(16).
4. dec: Read and write decimal values for integers i.e. setbase(10).
5. oct: Read and write octal values for integers i.e. setbase(10).
6. left: It adjusts output to the left.
7. right: It adjusts output to the right.

Manipulator -> Meaning


setw (int n) -> To set field width to n
setprecision (int p) -> The precision is fixed to p
setfill (Char f) -> To set the character to be filled
setiosflags (long l) -> Format flag is set to l
resetiosflags (long l) -> Removes the flags indicated by l
Setbase(int b) -> To set the base of the number to b
 setw () is a function in Manipulators in C++:
The setw() function is an output manipulator that inserts whitespace between
two variables. You must enter an integer value equal to the needed space.
Syntax:
setw ( int n)
As an example,
int a=15; int b=20;
cout << setw(10) << a << setw(10) << b << endl;

 setfill() is a function in Manipulators in C++:


It replaces setw(whitespaces )’s with a different character. It’s similar to setw()
in that it manipulates output, but the only parameter required is a single
character.
Syntax:
setfill(char ch)
Example:
int a,b;
a=15; b=20;
cout<< setfill(‘*’) << endl;
cout << setw(5) << a << setw(5) << a << endl;
 setprecision() is a function in Manipulators in C++:
It is an output manipulator that controls the number of digits to display after the
decimal for a floating point integer.
Syntax:
setprecision (int p)
Example:
float A = 1.34255;
cout <<fixed<< setprecision(3) << A << endl;
 setbase() is a function in Manipulators in C++:
The setbase() manipulator is used to change the base of a number to a different
value. The following base values are supported by the C++ language:
• hex (Hexadecimal = 16)
• oct (Octal = 8)
• dec (Decimal = 10)
The manipulators hex, oct, and dec can change the basis of input and output
numbers.

#include <iostream>

#include <iomanip>

using namespace std;

main()

int number = 100;

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

Input/output with files


C++ provides the following classes to perform output and input of characters
to/from files:

 ofstream: Stream class to write on files


 ifstream: Stream class to read from files
 fstream: Stream class to both read and write from/to 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:

// basic file operations [file example.txt]


#include <iostream> Writing this to a file.
#include <fstream>
using namespace std;

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

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::binaryOpen in binary mode.

Set the initial position at the end of the file.


ios::ate
If this flag is not set, the initial position is the beginning of the file.

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:

class default mode parameter

ofstreamios::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:

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

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

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:

// writing on a text file [file example.txt]


#include <iostream> This is a line.
#include <fstream> This is another line.
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;
}
Edit & run on cpp.sh

Reading from a file can also be performed in the same way that we did with cin:

// reading a text file This is a line.


#include <iostream> This is another line.
#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;
}
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.

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:

tellg() and tellp()


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:

// obtaining file size size is: 40 bytes.


#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;
}
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.

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 Description


type

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.

It is an alias of one of the fundamental integral types (such


streamoff ios::off_type
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.

You might also like