basic_istream::swap() in C++ with Examples

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Output:

Geeks Welcome

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Output:

Geeks forGeeks

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

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.