C++ IOS Library - tie



Description

It is used to get/set tied stream.

C++98

By default, cin is tied to cout, and wcin to wcout. Library implementations may tie other standard streams on initialization.

C++11

By default, the standard narrow streams cin and cerr are tied to cout, and their wide character counterparts (wcin and wcerr) to wcout. Library implementations may also tie clog and wclog.

Declaration

Following is the declaration for ios::tie function.

get (1)	ostream* tie() const;
set (2)	ostream* tie (ostream* tiestr);

The first form (1) returns a pointer to the tied output stream.

The second form (2) ties the object to tiestr and returns a pointer to the stream tied before the call, if any.

Parameters

tiestr − An output stream object.

Return Value

A pointer to the stream object tied before the call, or a null pointer in case the stream was not tied.

Exceptions

Basic guarantee − if an exception is thrown, the stream is in a valid state.

Data races

Accesses (1) or modifies (2) the stream object.

Concurrent access to the same stream object may cause data races.

Example

In below example explains about ios::tie function.

#include <iostream>     
#include <fstream>      

int main () {
   std::ostream *prevstr;
   std::ofstream ofs;
   ofs.open ("test.txt");

   std::cout << "tie example:\n";

   *std::cin.tie() << "This is inserted into cout";
   prevstr = std::cin.tie (&ofs);
   *std::cin.tie() << "This is inserted into the file";
   std::cin.tie (prevstr);

   ofs.close();

   return 0;
}

Let us compile and run the above program, this will produce the following result −

tie example:
This is inserted into cout
ios.htm
Advertisements