C++ Program to Demonstrate Use of Output String Stream

This C++ program illustrates use of output string stream. The class template std::basic_ostringstream implements output operations on memory based streams. This is used to attach stream to a string, that is we can write to it using this stream.

Here is the source code of the C++ program which illustrates use of output string stream. 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 use of output string stream
  3.  */
  4. #include <iostream>
  5. #include <string>
  6. #include <sstream>
  7. using namespace std;
  8.  
  9. string compose(int n, int id[], int age[], string name[])
  10. {
  11.     ostringstream os;
  12.  
  13.     os << "Id   : " << id[n - 1] << endl
  14.        << "Name : " << name[n - 1] << endl
  15.        << "Age  : " << age[n - 1] << endl;
  16.     return os.str();
  17. }
  18.  
  19. int main()
  20. {
  21.     int id[] = {1, 2, 3, 4, 5}, n;
  22.     int age[] = {21, 23, 22, 21, 20};
  23.     string name[] = {"Alice", "Bob", "Charles", "Danny", "Emily"};
  24.  
  25.     cout << "Enter id (1 - 5) : ";
  26.     cin >> n;
  27.     cout << "Details\n";
  28.     cout << compose(n, id, age, name);
  29. }

$ a.out
Enter id (1 - 5) : 1
Details
Id   : 1
Name : Alice
Age  : 21

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

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

advertisement
advertisement
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.