C++ Program to Illustrate Usage of String Streams

This C++ program illustrates usage of string streams. The std::stringstream is a stream class to operate on strings whose instantiations use string buffer that contain sequence of characters. This sequence of characters can be directly accessed as a string object. The characters can be extracted and inserted using any operation allowed on input and output streams.

Here is the source code of the C++ program which illustrates usage of string streams. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to illustrate usage of string streams
  3.  */
  4. #include <iostream>    
  5. #include <sstream>   
  6. #include <string>       
  7. using namespace std;
  9. int main () {
  10.     stringstream ss;
  11.     string s;
  13.     cout << "Enter your first name\n";
  14.     cin >> s;
  15.     ss.str(s);
  16.     cout << "Enter your last name\n";
  17.     cin >> s;
  18.     ss.str(ss.str() + " " + s);
  19.     cout << "Hello " << ss.str() << "!\n";
  20. }

$ gcc test.cpp
$ a.out
Enter your first name
Enter your last name
Hello George Harrison!

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

If you wish to look at all C++ Programming examples, go to C++ Programs.

Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.