Skip to content
Related Articles

Related Articles

Improve Article
basic_istream::swap() in C++ with Examples
  • Last Updated : 28 May, 2020

The basic_ios::swap(x) is used swap all data members of the base class except for rdbuf(), and swaps the values of the gcount() counters between *this and x. This basic_ios::swap(x) function is a protected function. Below is the syntax and the header file for the same:

Header File:

#include<iostream>

Syntax:

void swap (basic_istream& x);

Parameter: It accepts the following parameter:

  • x : It represents the another object with the same parameter.

Return Value: The method basic_istream::get() doesn’t return anything.



Below are the programs to demonstrate basic_istream::swap():

Program 1:




// C++ program to demonstrate
// basic_istream::swap()
  
#include <bits/stdc++.h>
using namespace std;
  
// Driver Code
int main()
{
    // Input String gfg1
    istringstream gfg1("Welcome");
  
    // Input String gfg2
    istringstream gfg2("Geeks");
  
    // swap function for swapping
    // both the strings
    swap(gfg1, gfg2);
    cout << gfg1.rdbuf() << " "
         << gfg2.rdbuf() << endl;
  
    return 0;
}
Output:
Geeks Welcome

Program 2:




// C++ program to demonstrate
// basic_istream::swap()
  
#include <bits/stdc++.h>
using namespace std;
  
// Driver Code
int main()
{
    // Input String gfg1
    istringstream gfg1("forGeeks");
  
    // Input String gfg2
    istringstream gfg2("Geeks");
  
    // swap function for swapping
    // both the strings
    gfg1.swap(gfg2);
    cout << gfg1.rdbuf() << " "
         << gfg2.rdbuf() << endl;
  
    return 0;
}
Output:
Geeks forGeeks

Reference: http://www.cplusplus.com/reference/istream/basic_istream/swap/

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :