The C++ std::stringstream::swap() function is used to exchange the content of two stringstream objects along with their internal states including their buffer contents and state flags. By invoking this function, we can transfer the data between two streams without the need for copying or re-initializing.
SyntaxFollowing is the syntax for std::stringstream::swap() function.
void swap (stringstream& x);Parameters
This function does not return anything.
ExceptionsThis function never throws exceptions.
Data racesModifies both stream objects (*this and x).
ExampleIn the following example, we are going to consider the basic usage of the swap() function.
#include <iostream> #include <sstream> int main() { std::stringstream a, b; a << "Namaste"; b << "Vanakam"; a.swap(b); std::cout << "After swapping :" << std::endl; std::cout << "a : " << a.str() << std::endl; std::cout << "b : " << b.str() << std::endl; return 0; }Output
Output of the above code is as follows −
After swapping : a : Vanakam b : NamasteExample
Consider the following example, where we are going to swap with empty stream.
#include <iostream> #include <sstream> int main() { std::stringstream x, y; x << "TutorialsPoint"; x.swap(y); std::cout << "After swapping :" << std::endl; std::cout << "x : " << x.str() << std::endl; std::cout << "y : " << y.str() << std::endl; return 0; }Output
Following is the output of the above code −
After swapping : x: y: TutorialsPointExample
Let's look at the following example, where we are going to use the swap() function with identical streams.
#include <iostream> #include <sstream> int main() { std::stringstream x; std::stringstream y; x << "Hi"; y << "Hi"; x.swap(y); std::cout << "After swapping :" << std::endl; std::cout << "x : " << x.str() << std::endl; std::cout << "y : " << y.str() << std::endl; return 0; }Output
If we run the above code it will generate the following output −
After swapping : x : Hi y : Hi
istream.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4