C++ streams
In C++, a stream refers to a sequence of characters that are transferred between the program and
input/output (I/O) devices. Stream classes in C++ facilitate input and output operations on files and other
I/O devices. These classes have specific features to handle program input and output, making it easier to
write portable code that can be used across multiple platforms.
To use streams in C++, we need to include the appropriate header file. For instance, to use input/output
streams, we would include the iostream header file. This library provides the necessary functions and
classes to work with streams, enabling you to read and write data to and from files and other I/O devices.
The four essential C++ stream classes:
1. istream
2. ostream
3. ifstream
4. ofstream
1. istream class
This class is a general-purpose input stream and is used to read input from various sources,
including the console and files. The istream class provides a range of functions for handling
characters, strings, and objects, including get, getline, read, ignore, putback, and cin.
One example of an istream is cin, which is a commonly used input stream for reading input
from the console
#include <iostream>
using namespace std;
int main()
{
char a;
[Link](a);
cout << a;
return 0;
}
2. Ostream class
It is responsible for output operations. It provides functions to write characters, strings, and objects,
such as:
• write()
• put()
#include <iostream>
using namespace std;
intmain()
{
char u;
[Link](u);
[Link](u);
3. ifstream class
An ifstream object represents an input file stream, which is used to read data from a file. Since
an ifstream is a type of istream, any operations that can be performed on an istream can also be
performed on an [Link] common example of an istream is cin, which is used for standard input.
Therefore, any operations that you can perform with cin can also be performed with an ifstream object.
We need to include the fstream header by adding the following line at the beginning of your program:
#include <fstream>
4. Ofstream class
An ofstream is an output file stream, and works exactly like ifstreams, except for output instead of
[Link] an ofstream is created, opened, and checked for no failures, we can use it just like cout
1 ofstream fout( "[Link]" );
2 fout << "The minimum oxygen percentage is " << minO2 << endl;
Some common use cases for C++ streams include:
1. Reading and writing to files – C++ streams provide a convenient way to read and write data to
and from files. This can be used to create log files, read configuration files, and more.
2. Parsing input – C++ streams can be used to parse input data, such as reading data from a CSV
file or parsing command-line arguments.
3. Debugging – C++ streams can be used to output debugging information, such as the value of
variables, to the console or a file.
4. Network programming – C++ streams can be used to read and write data over a network
connection, such as when creating a client-server application.
File Reading Functions
File reading functions extract characters from a file and move the file pointer.
1. get()
The get() method reads a single character from a file and returns its ASCII value as an int value.
Convert it to a char type to see the character. The file pointer is moved to the next character in
the file.
char myChar = [Link]();
cout << myChar;
The get (destination, size, delimiter) method writes up to size characters to the destination with
data read from the file. It stops reading as soon as it reaches a line break, end of file, or an
optional character given by the delimiter parameter. The value written in destination always ends
with a \0 null terminating character. This method moves the file pointer to the line break or
delimiter where it stopped reading.
char destination[20];
[Link](destination, 20);
cout << destination << "\n";
// Stop reading when a '.' is found
[Link](destination, 20, '.');
cout << destination << "\n";
2. getline()
The C++ getline() is a standard library function that is used to read a string or a line from an
input stream. It extracts the characters from the input stream and appends it to the given string
object until the delimiting character is encountered.
#include <bits/stdc++.h>
using namespace std;
int main() {
string name;
// Taking input from cin stream(standard
// input stream) and storing it in name
getline(cin, name);
cout << name;
return 0;
}
Syntax of getline()
The std::getline() function is defined inside <string> header file in C++.
getline(stream, str, delim);
Parameters:
• stream: Input stream from where characters are read.
• str: String where the input is stored after being read from the stream.
• delim(optional): Delimiter is a character where getline stop to read the data. By default,
newline character '\n' is the delimiter.
•
To read space separated user input. if we try to read the space separated string from cin stream
using >> operators, it only reads the first word. Because whitespace character ' ' is the delimiter
for cin. It can be done with getline().
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
// Read input from cin
getline(cin, str);
cout << "Hello, " << str
<< " welcome to GFG !";
return 0;
}
Output
Harsh Agarwal (Enter by user)
Hello, Harsh Agarwal welcome to GFG
Put function
The put function is used to write a single character to the output stream. It is useful for low level
character output operations. It takes a single argument of type char, representing the character to
be written, and returns a reference to the output stream.
The syntax for std::ostream::put() function is
ostream& put (char c);
where c indicates the character to write.
Put function returns the ostream object (*this).
#include <iostream>
int main()
{
std::[Link]('A');
return 0;
}
Output
Write() function
The write() function is used to write a block of characters (a C-style string or character array) to
the output stream. The syntax is
ostream& write(const char* s, streamsize n);
It takes two arguments:
Where “const char* s” is a pointer to the beginning of the character array (or C-style string) to
be written and “streamsize n” is the number of characters to write from the array.
#include <iostream>
#include <string>
int main() {
std::string message = "Hello, C++ streams!";
std::[Link](message.c_str(), [Link]());
std::[Link]('\n'); // Newline character
return 0;
}
In the above example, message.c_str() provides a const char* pointer to the string's data,
and [Link]() provides the number of characters to write.
Formatted Input-Output Operations in C++
Formatting is the process of transforming a byte sequence into a human-readable character
sequence. Internal representation of numeric data is in binary; need not be in human readable
form. Text I/O involves formatting or converting the data into the external representation as a
sequence of characters. Iostreams allow controllingsuch formatting features inmany ways with
the help of formatting [Link] iostreams, one can specify:
• The width of the field and the adjustment of the outputwithin this field;
• The decimal point to be aligned;
• The precision and format of floating point numbers;
• Whether to skip white spaces when reading from aninput stream;
• Whether integral values are displayed in decimal, octal or hexadecimal format;
Formatting Flags
Formatting control is possible via a stream’s format state. Associated with each stream, there
are a number of format state variables that control the details of formatting. These variables are
defined in ios class. Formatting flags are represented by one or more bits in a data member of
type fmtflags in class ios_base. It is defined as enumerated data type. The bits act as on/off
switches that specify various formats as shown below.
Format Group Default i/o Effect
flag
Left-align, padding with fill character on
left adjustfield right o
right
right Right-align, padding with fill character on
left
padding between sign or base indicator
internal
and number [-12.34]
dec basefield dec i,o integer to decimal form
oct integer to octal form
hex integer to hexadecimal for
Formatting using ios functions
The ios class contains a number of functions that can be used to set/unset the formatting flags
and perform other tasks using format state variables.
Function Default Effect
width() 0 Minimum field with to be used
precision() 6 Precision for number of digits after decimal point
Space
fill() Fill character to be used for padding
character
setf() 0 Set bit of format flag
unsetf() 0 Reset bit of format flag
Function width()
Function width() is used to get/set width variable. Width specifies number of characters or
positions to be used during input/output. Even though it can be used during input, it is more
meaningful to use it for output purpose.
• Syntax: int ios::width (int num=0)
• Sets the field width to num Returns the previous value of width parameter.
• Default is 0, which means to use as many characters as necessary.
• Thewidth setting is not permanent. The value of the width format variableis reset to zero
(the default) after its use.
• For output, num is the minimum width to be used.
For example:
int i=1234; char* str[10]=”Hello”;
[Link](7);
cout<<i << str;
In the above example, value of the first item i will be displayed using a width of 7 positions and
the width parameter will be reset to its default value 0. Now, value of str will be displayed using
minimum width 0; i.e 5 positions as necessary.
Function fill()
Function fill() is used to get/set fill character used as padding character to fill extra
[Link]: char ios::fill (char padding = ‘ ’)
• Set the padding character to be used to fill extra positions
• Default: blank; a space character
• Permanent setting, remain in effect until changed
For example:
[Link](7);
[Link] (‘*’);
cout << 1234;
[Link](7);
cout << “Hello”;
Output will be: ***1234**Hello
Function precision()
This function is used to specify number of significant digits in case of floating point numbers.
It also returns the old value of precision.
Syntax: int ios::precision (int num = 6)
• Set the number of significant digits to num for input and output of floating point numbers
• Default precision is of 6 significant digits
• Remains in effect until changed
• When specified precision is shorter than required
• Performs rounding of digits after decimal point
• If not enough to accommodate integral part, it uses scientific format
For example:
[Link] (‘*’);
[Link](7);
[Link](10);
cout << 1234.567<< endl;
[Link](8);
[Link](10);
cout << 1234.567<< endl;
[Link](5);
[Link](10);
cout << 1234.567<< endl;
[Link](3);
[Link](10);
cout << 1234.567<< endl;
Output is:
**1234.567
**1234.567
****1234.6
*1.23e+003
setf()
Format flags (bits of format flag variable) can be set using setf() function in two forms as
follows.
Syntax:
fmtflags ios::setf (fmtflags flg)
fmtflags ios::setf (fmtflags flg, fmtflags mask)
• Sets format flags as specified in first argument
• Returns old value of format flags
• To specify format flags, precede flag name with the class name ios and the scope-
resolution operator (for example, ios::fixed)
• To set multiple flags, use OR (|) operator to combine them (for example, ios::fixed |
ios_base::uppercase )
• Two-argument version of setf()
• Some format flags are grouped, because they are mutually exclusive.
Formatting using manipulators
Manipulators are also used to perform the task of formatting input/output. Manipulators are
special type of non-member functionsthat can be included in an insertion or extraction chain.
Manipulators are non-member functions returning a reference to a stream. So they can be used
with shift operator in cascaded fashion. Manipulators are non-member functions, so they do not
require to be called using dot operator with stream objects.
Following table lists the manipulators equivalent to ios functions.
Manipulator Equivalent ios member function
setw() width()
setprecision() precision()
setfill() fill()
setiosflags() setf()
resetiosflags() unsetf()