Friday, May 28, 2021

C++ iostream class

INTRODUCTION

C++ uses the concept of streams and stream classes to implement its I/O operations with the console and disk files. In C++ programming language, input/output library refers to a family of class templates and supporting functions in the C++ Standard Library that implement stream-based input/output capabilities. The I/O stream in C++ is created to work with wide range of devices such as terminals, disks and tape devices. Each device is very different therefore, I/O system provides an interface that is independent of actual device being accessed. This interface is known as streams. C++ IO is type safe. IO operations are defined not only for a particular type but each type or else the compiler will generate error.

What is <iostream>?

Iostream stands for standard input and output stream. C++ I/o streams are primarily defined by iostream, a header file which is a part of C++ standard library. In C++ like C has no built-in syntax for streaming data input and output, no keyword like read or write. Rather, these facilities are provided by a library. Including <iostream> automatically includes <ios>, <streambuf>, <istream>, <ostream> and <iosfwd>. The header files include objects from <istream> and <ostream> like cin, cout, cerr, clog etc.

  • cin - This is the of standard input stream, usually keyboard.
  • cout - This is of standard output stream, usually screen of the monitor.
  • cerr - This is standard error output stream, usually screen of the monitor.
  • clog - This is another version of cerr. It provides buffer to collect errors

 

STREAM CLASSES

C++ stream is a sequence of bytes, these bytes could represent chars, raw data, graphics, digital speech, digital video or any other information. I/O stream mechanism acts as a source to transfer bytes from input stream to main memory and main memory to output stream. C++ consists of hierarchy of classes called stream classes used for input and output operations with console unit. All these classes are defined in iostream.h header file figure below represents this hierarchy of classes.



 

Ios is the base class for istream and ostream, which are base classes for iostream. ios_base provides support and defines all the basic properties required for formatted and unformatted I/O operations. It is the mother of the all base classes which contains most of the I/O code. Most of this class comprises of components and functions for state and format flags. istream(basic_istream<>) and ostream(basic_ostream<>) provides input and output interfaces, derived virtually from basic_ios<> and defines objects that can be used for reading and writing. iostream derives from both istream and ostream and defines objects that can be used for both reading and writing. streambuf provides and interface to physical devices through buffers.

IOSTREAM CLASS

The iostream class is derived from istream and ostream by multiple inheritance and hence offers functionality of both classes. Class ios is inherits indirect into iostream class using istream and ostream. ios class is declared as a virtual base class while inheriting in istream and ostream to avoid duplicity of data and member functions. This class is mainly declared in header <istream>. It provides functionality to work with the objects, strings and chars which includes inbuild functions such as get, getline, read, ignore, putback, put, write etc.

The public member function, constructor present in iostream behave exactly like constructor in istream class.

  • Constructor: iostream::iostream() – when this is used without arguments, the constructor for iostream simply allocates a new ios object and the input counter is initialized to 0.
  • Constructor: iostream::iostream(streambuf*sb[,ostream*tie]) – a constructor can also be called with one or two arguments. As we can see in the above syntax, the first argument sb is a streambuf i.e., if we supply this pointer, the constructor uses this streambuf for input and output. We can also use the optional second argument tie to specify a related output as the initial value for ios::tie.

Iostream simply uses the ios destructor, but an iostream is deleted by its destructor.

The protected member functions present in iostream are:

  • Operator ‘=’ – move assignment
  • Swap – swap internals

UNFORMATTED I/O OPERATIONS

We know that the objects cin and cout which are predefined in the iostream file are used for input and output of various datatypes. This is mainly possible due to overloading of operators >> and <<  which are used to recognize all the basic C++ types. The operator >> is overloaded in istream and << is overloaded in ostream, and both these are included in iostream class. Let us look at the example below.

#include <iostream> 
using namespace std; 
int main()
{
char output[] = "iostream.h";
cout << output<< " - A header file that defines all the classes.";
return 0;
}

 OUTPUT

               iostream.h – A header file that defines all the classes.

In the program above, the cout statement is an instance of ostream class, used to produce output which is displayed on standard output device, like display screen. The data is inserted in cout using the insertion operator (<<).

Look at the code below to understand cin statement which an instance of class iostream


#include <iostream>
using namespace std;
int main()
{
int x;
cout << "Enter a number:";
cin >> x;
cout << "\nNumber you chose is - " << x;

return 0;
}

The operator (>>) known as extraction operator is used with object cin to read inputs. This operator extracts data from object entered through input device, which is keyboard.

put() and get()  FUNCTION

put() and get are member functions defined by the classes ostream and istream respectively. Both are used to handle single character I/O operations.

Get()

It is a member of istream class which is used to input a single character at a line. Two types of get() functions are present that are, get(char*) and get(void). These both prototypes can be used to get character, also including blank space, tab and newline character. In get(char*), the input character is assigned to its argument. Let’s look at the example given below.


#include <iostream>
using namespace std;
int main()

char x[15];
cin.get(x, 15);
while(x!= ‘/n’)
{
cout << x ;
}
return 0;
}

INPUT

            Amazon forest   

OUTPUT

            Amazon forest

The while loop present in the code above wouldn’t have worked if cin >> x was used in place of cin.get(x). This is because the cin extraction operator (>>) terminates when white space or newline character is found.

get(void) is very simple to understand. It just assigns the value returned by the function get() to the variable.

Example:

char c;

c = cin.get();

we can notice that cin.get(c) has been replaced by c = cin.get();

put()

This function is a member of ostream class is used to output a line of text, character by character. Check out the example below,

  • cout.put(‘x’); - this statement displays the character x
  • cout.put(ch); - this statement displays the value of variable ch which is assigned using an input device such as keyboard and it must contain a character value.

A number as an argument to the function can also be used. Like,

  • cout.put(68); - this statement converts the int value to a char value and will display a character whose ASCII value is the number mentioned. For this statement, it will display the character D.

the code below shows the working of put() function


#include <iostream>
using namespace std;
int main()
{
char char;
cin.get(char); // will scan a single char
cout.put(char); // will put a single char onto the screen.
}

 

 INPUT

             x

OUTPUT

             x


getline() and write() functions

The reading and displaying of line of a text can be done more efficiently using the line-oriented I/O functions getline() and write().

getline()

In C++ sometimes there is a need to enter multiple strings, like a line or a paragraph. Using cin we cannot input multiple strings once. This function can be used to read a whole line of text that ends with a newline character which is transmitted using RETURN key. The syntax of this function is:

cin.getline(line, size);

this is the older version which was used when strings weren’t introduced. At that time the input as string was taken in the form of array of characters.

Example:

char stng[1000]
cin.getline(stng, 1000);

In the newer version when string was introduced, we can input string directly as:

string sttng
getline(cin, sttng);

let us understand a bit more clearly through the code below

#include<iostream>
using namespace std;
int main()
{
string strin;

cout<<"Enter the String "<<endl<<endl;

getline(cin,strin);

cout<<"You enterd : "<<endl;

cout<<strin;

return 0;
}

INPUT

        Hey there, this is my first program.

OUTPUT

        You entered:

        Hey there, this is my first program.

 

Write()

This function is used to display an entire line, its syntax is:

    cout.write(line, size)

In the above statement, the first argument represents the name of string which is to be displayed whereas the second one, size indicates number of characters to display. Remember that, when a null character is present, it does nit stop displaying the characters. If size is greater than length, it displays beyond the line.


#include <iostream>

using namespace std;

int main()

{

    cout.write("Acknowledgement", 5);

}

OUTPUT

               Ackno

We can also concatenate using this function. 

        cout.write(string1, m). cout.write(string2, n);

The above statement is equivalent to

  1. cout.write(string1, m);
  2. cout.write(string2, n);

 

FORMATTED I/O OPERATIONS 

There are number of features supported by C++ that are used for formatting the output. These are:

  • ios class functions and flags

This class contains huge number of member functions that help in formatting the output in various ways. Some of them are:

  1.  width(): used to set the required field width. The output will be displayed in the given width.
  2. precision():used to set the number of the decimal point to a float value
  3. fill(): used to set a character to fill in the blank space of a field
  4. setf(): used to set various flags for formatting output
  5. unsetf(): used To remove the flag set

This class contains format flags that control the way of formatting i.e., using the setf function, with this we can set flags that allow us to display a value in some particular format. The bitmask enumeration called fmtflags defines all the values like showbase, showpoint etc. this is declared in ios class.


  • C++ manipulators.

Manipulators are special helping functions that can be included to modify or alter the format parameters of the stream. It doesn’t mean that we are changing the value of a variable it means simply modifying it using ‘<<’ and ‘>>’ operators. 

Important manipulators are:

  1. endl – it is used to enter a newline and flushes after entering the new line. It is defined in ostream.
  2. ws – used to ignore whitespaces present in string sequence. Defined in istream.
  3. ends – it inserts a null character into output stream. It is used when associated output buffer requires to be null- terminated to be processed as a c string.
  4. flush – defined in ostream, flushes the output stream which means it flushes all the output on the screen or file. If we don’t use it, the output will be same it just may not appear in real-time.


Other public member functions inherited from istream              

  • gcount - To get character count
  • ignore – To extract and discard characters
  • peek- To peek next character
  • read – To read block of data

 Other public member functions inherited from ostream

  • tellp - Get position in output sequence
  • seekp - Set position in output sequence

 

 



REFERENCES:-

www3.ntu.edu.sg

www.cplusplus.com

www.geeksforgeeks.org

Books - 

Object oriented programming with C++ by E Balaguruswamy



No comments:

Post a Comment

Importance of prediction of thermodynamic properties

 PREDICTION OF THERMODYNAMIC PROPERTIES