2. ios:base class for all input output operation
istream: get, getline, read, ignore, putback
ostream:write, put
iostream:cin, cout, cerr and clog
Templates istream and
ostream both derive through
single inheritance from base
template ios.
Template iostream derives
through multiple inheritance
from templates istream and
ostream.
3. Introduction
• The C++ standard libraries provide an extensive set of input/output
capabilities.
• C++ uses type-safe I/O.
• Each I/O operation is executed in a manner sensitive to the data type.
• If an I/O function has been de-fined to handle a particular data type,
then that member function is called to handle that data type.
• If there is no match between the type of the actual data and a function
for handling that data type, the compiler generates an error.
• Thus, improper data cannot “sneak” through the system.
4. Streams
• C++ I/O occurs in streams, which are sequences of bytes.
• In input operations, the bytes flow from a device (e.g., a keyboard, a
disk drive, a network connection, etc.) to main memory.
• In output operations, bytes flow from main memory to a device (e.g.,
a display screen, a printer, a disk drive, a network connection, etc.).
• The time these transfers take is typically much greater than the time
the processor requires to manipulate data internally.
• Thus, I/O operations require careful planning and tuning to ensure
optimal performance.
5. Streams (cont.)
• C++ provides both “low-level” and “high-level” I/O capabilities.
• Low-level I/O capabilities (i.e., unformatted I/O) specify that some
number of bytes should be transferred device-to-memory or memory-
to-device.
• In such transfers, the individual byte is the item of interest.
• Such low-level capabilities provide high-speed, high-volume transfers
but are not particularly convenient.
• Programmers generally prefer a higher-level view of I/O (i.e.,
formatted I/O), in which bytes are grouped into meaningful units,
such as integers, floating-point numbers, characters, strings and user-
defined types.
• These type-oriented capabilities are satisfactory for most I/O other
than high-volume file processing.
6. iostream Library Headers
• The C++ iostream library provides hundreds of I/O
capabilities.
• Several headers contain portions of the library interface.
• Most C++ programs include the <iostream> header, which
declares basic services required for all stream-I/O operations.
• The <iostream> header defines the cin, cout, cerr and
clog objects, which correspond to the standard input stream,
the standard output stream, the unbuffered standard error stream
and the buffered standard error stream, respectively.
• Both unformatted- and formatted-I/O services are provided.
7. iostream Library Header s (cont.)
• The <iomanip> header declares services useful for performing
formatted I/O with so-called parameterized stream manipulators, such
as setw and setprecision.
• C++ implementations generally contain other I/O-related libraries that
provide sys-tem-specific capabilities, such as the controlling of
special-purpose devices for audio and video I/O.
8. Stream Input/Output Classes and
Objects (cont.)
• Predefined object cin is an istream instance and is said to be
“connected to” (or attached to) the standard input device, which
usually is the keyboard.
• The predefined object cout is an ostream instance and is said to
be “connected to” the standard out-put device, which usually is the
display screen.
9. Stream Input/Output Classes and
Objects (cont.)
• The predefined object cerr is an ostream instance and is said to
be “connected to” the standard error device, normally the screen.
• Outputs to object cerr are unbuffered, implying that each stream
insertion to cerr causes its output to appear immediately—this is
appropriate for notifying a user promptly about errors.
• The predefined object clog is an instance of the ostream class and
is said to be “connected to” the standard error device.
• Outputs to clog are buffered.
• This means that each insertion to clog could cause its output to be
held in a buffer until the buffer is filled or until the buffer is flushed.
10. Character Output Using Member
Function put
• We can use the put member function to output characters.
• For example, the statement
• cout.put( 'A' );
• displays a single character A.
• Calls to put may be cascaded, as in the statement
• cout.put( 'A' ).put( 'n' );
• which outputs the letter A followed by a newline character.
• As with <<, the preceding statement executes in this manner, because
the dot operator (.) associates from left to right, and the put member
function returns a reference to the ostream object (cout) that
received the put call.
• The put function also may be called with a numeric expression that
represents an ASCII value, as in the following statement
• cout.put( 65 );
• which also out-puts A.
11. Stream Input
• Formatted and unformatted input capabilities are provided by istream.
• The stream extraction operator (>>) normally skips white-space characters
(such as blanks, tabs and newlines) in the input stream; later we’ll see how to
change this behavior.
12. get and getline Member
Functions
• The get member function with no arguments inputs one character
from the desig-nated stream (including white-space characters and
other nongraphic characters, such as the key sequence that represents
end-of-file) and returns it as the value of the function call.
• This version of get returns EOF when end-of-file is encoun-tered on
the stream.
• The user enters a line of text and presses Enter followed by end-of-
file (<Ctrl>-z on Microsoft Windows systems, <Ctrl>-d on UNIX
and Macintosh systems).
• This program uses the version of istream member function get
that takes no arguments and returns the character being input
13. get and getline Member
Functions (cont.)
• The get member function with a character-reference argument inputs
the next character from the input stream (even if this is a white-space
character) and stores it in the character ar-gument.
• This version of get returns a reference to the istream object for
which the get member function is being invoked.
• A third version of get takes three arguments—a character array, a
size limit and a delimiter (with default value 'n').
• This version reads characters from the input stream.
• It either reads one fewer than the specified maximum number of
characters and terminates or terminates as soon as the delimiter is
read.
• A null character is inserted to terminate the input string in the
character array used as a buffer by the pro-gram.
• The delimiter is not placed in the character array but does remain in
the input stream (the delimiter will be the next character read).
16. istream Member Functions peek,
putback and ignore
• The ignore member function of istream reads and discards
a designated number of characters (the default is one) or
terminates upon encountering a designated delimiter (the
default is EOF, which causes ignore to skip to the end of the
file when reading from a file).
• The putback member function places the previous character
obtained by a get from an input stream back into that stream.
• This function is useful for applications that scan an input stream
looking for a field beginning with a specific character.
• When that character is input, the application returns the character to
the stream, so the character can be included in the input data.
• The peek member function returns the next character from an
input stream but does not remove the character from the stream.
17. Introduction to Stream Manipulators
• C++ provides various stream manipulators that perform formatting
tasks.
• The stream manipulators provide capabilities such as setting field
widths, setting precision, setting and unsetting format state, setting
the fill character in fields, flushing streams, inserting a newline into
the output stream (and flushing the stream), inserting a null character
into the output stream and skipping white space in the input stream.
• These features are described in the following sections.
21. Floating-Point Precision
(precision, setprecision)
• We can control the precision of floating-point numbers (i.e., the
number of digits to the right of the decimal point) by using
either the setprecision stream manipulator or the
precision member function of ios_base.
• A call to either of these sets the precision for all subse-quent
output operations until the next precision-setting call.
25. Field Width (width, setw)
• The width member function (of base class ios_base) sets the field width
(i.e., the number of character positions in which a value should be output or
the maximum number of characters that should be input) and returns the
previous width.
• If values output are narrower than the field width, fill characters are inserted
as padding.
• A value wider than the designated width will not be truncated—the full
number will be printed.
• The width function with no argument returns the current setting.
• Figure demonstrates the use of the width member function on both input
and output.
• On input into a char array, a maximum of one fewer characters than the
width will be read.
• Remem-ber that stream extraction terminates when nonleading white space is
encountered.
• The setw stream manipulator also may be used to set the field width.
31. Justification (left, right and
internal)
• Stream manipulators left and right enable fields to be left
justified with padding characters to the right or right justified with
padding characters to the left, respectively.
• The padding character is specified by the fill member function or
the setfill parameterized stream manipulator
• uses the setw, left and right manipulators to left justify and
right justify integer data in a field.
32. Uppercase/Lowercase Control
(uppercase)
• Stream manipulator uppercase outputs an uppercase X or E with
hexadecimal-integer values or with scientific notation floating-point
values, respectively
• Using stream manipulator uppercase also causes all letters in a
hexadecimal value to be uppercase.
• By default, the letters for hexadecimal values and the exponents in
scientific notation floating-point values appear in lowercase.
• To reset the uppercase setting, output the stream manipulator
nouppercase.
34. File handling in C++ is a mechanism to store
the output of a program in a file and help
perform various operations on it. Files help
store these data permanently on a storage
device.
37. Create a file
Open a file
Read from a file
Write to a file
Close a file
open() – This is used to create a file.
read() – This is used to read the data from the file.
write() – This is used to write new data to file.
close() – This is used to close the file.
38. fstream library
Before diving into each sub-topics, let us first learn about the header file we will be using to
gain access to the file handling method. In C++, fstream library is used to handle files, and it is
dealt with the help of three classes known as ofstream, ifstream and fstream.
ofstream:
This class helps create and write the data to the file obtained from the program’s output. It is
also known as the input stream.
ifstream:
We use this class to read data from files and also known as the input stream.
fstream:
This class is the combination of both ofstream and ifstream. It provides the capability of
creating, writing and reading a file.
To access the following classes, you must include the fstream as a header file like how we
declare iostream in the header.
Example:
#include<iostream>
#include<fstream>
After including the header file, there comes a question saying do we need to create the file
within the program or else do we need to use an existing file. But this isn’t that difficult to
answer because, in C++, we get four different methods to handle files. Let’s discuss them one
39. Opening files in C++
To read or enter data to a file, we need to open it first. This can be performed with the
help of ‘ifstream’ for reading and ‘fstream’ or ‘ofstream’ for writing or appending to the
file. All these three objects have open() function pre-built in them.
Syntax:
open( FileName , Mode );
Here:
FileName – It denotes the name of file which has to be opened.
Mode – There different mode to open a file and it explained in this article.
41. 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<iostream>
#include<fstream>
using namespace std;
int main(){
fstream FileName;
FileName.open("FileName", ios::out);
if (!FileName){
cout<<"Error while creating the file";
}
else{
cout<<"File created successfully";
FileName.close();
}
return 0;
}
Program for Opening File:
1.Here we have an iostream library, which is responsible for
input/output stream.
2.We also have a fstream library, which is responsible for handling files.
3.Creating an object of the fstream class and named it as ‘FileName’.
4.On the above-created object, we have to apply the open() function to
create a new file, and the mode is set to ‘out’ which will allow us to write
into the file.
5.We use the ‘if’ statement to check for the file creation.
6.Prints the message to console if the file doesn’t exist.
7.Prints the message to console if the file exists/created.
8.We use the close() function on the object to close the file.
Output
File created successfully
42. Writing to File
Till now, we learned how to create the file using C++. Now, we will learn how to write data
to file which we created before. We will use fstream or ofstream object to write data into
the file and to do so; we will use stream insertion operator (<<) along with the text
enclosed within the double-quotes.
With the help of open() function, we will create a new file named ‘FileName’ and then we
will set the mode to ‘ios::out’ as we have to write the data to file.
Syntax:
FileName<<"Insert the text here";
43. 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<iostream>
#include<fstream>
using namespace std;
int main() {
fstream FileName;
FileName.open("FileName.txt", ios::out);
if (!FileName) {
cout<<" Error while creating the file ";
}
else {
cout<<"File created and data got written to file";
FileName<<"This is a blog posted on Great Learning";
FileName.close();
}
return 0;
}
Program for Writing to File:
1.Here we have an iostream library, which is responsible for input/output stream.
2.We also have a fstream library, which is responsible for handling files.
3.Creating an object of the fstream class and named it as ‘FileName’.
4.On the above-created object, we have to apply the open() function to create a new file, and the
mode is set to ‘out’ which will allow us to write into the file.
5.We use the ‘if’ statement to check for the file creation.
6.Prints the message to console if the file doesn’t exist.
7.Prints the message to console if the file exists/created.
8.Writing the data to the created file.
9.We use the close() function on the object to close the file.
Output
File created and data got written to file