C++ Program to Demonstrate Use of Output String Stream

bookmark

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
 
string compose(int n, int id[], int age[], string name[])
{
    ostringstream os;
 
    os << "Id   : " << id[n - 1] << endl
       << "Name : " << name[n - 1] << endl
       << "Age  : " << age[n - 1] << endl;
    return os.str();
}
 
int main()
{
    int id[] = {1, 2, 3, 4, 5}, n;
    int age[] = {21, 23, 22, 21, 20};
    string name[] = {"Alice", "Bob", "Charles", "Danny", "Emily"};
 
    cout << "Enter id (1 - 5) : ";
    cin >> n;
    cout << "Details\n";
    cout << compose(n, id, age, name);
}

 

Output:
Enter id (1 - 5) : 1
Details
Id   : 1
Name : Alice
Age  : 21