Tuesday, June 9, 2009

std::ostringstream AKA String Streams...

Want to share a few bits about a very important and useful feature of standard library today. std::ostringstream can come in handy in many situation. You know we often need to concatenate strings. And often it becomes tedious, usually this is done using strcat funtion in C and + operator in C++  std::string class . For example

// C style

char * szFullName = strcat("First Name ", " Last Name");


//C++ style
std::string strFirstName = "First Name";
std::string strLastName = "Last Name";
std::string strFullName = strFirstName + " " + strLastName;

std::ostringstream gives us a convenient way to build strings conveniently.
std::ostringstream provides functionality very much similar to sprintf function of C language.

Like for example you got names, ages, and heights of a few kids stored in arrays and you want them to be printed nicely on screen. Perhaps you could use a std::string and + operator to join string but I think using ostringstream will be a better approach.

Preview (hint: you can copy and paste the preview into Microsoft Word):
const int CONST_ARRAY_SIZE = 3;
std::string aryStrNames[CONST_ARRAY_SIZE] = {"Ali", "Jason", "Shiv"};
int aryNAges[CONST_ARRAY_SIZE] = {5,9,11};
float aryFHeight[CONST_ARRAY_SIZE]={3.2,4.0,4.4};
std::ostringstream outBuffer;
for(int i = 0; i < CONST_ARRAY_SIZE; i++){
outBuffer<<aryStrNames[i]<" is " << aryNAges[i] << " years old, and his height is "<< aryFHeight[i] << endl;
}// end for i
cout<< outBuffer.str();

Here's a link to ostringstream on C Plus Plushttp://www.cplusplus.com/reference/iostream/ostringstream/



No comments:

Post a Comment

Feel free to talk back...