I'm getting a very strange output from a function of mine. The idea is for it to format string information of an item in a catalog (a map, with int key and "Product" value), for display in the terminal window. The string information is held in a std::vector. I won't bore you with the details: what's strange (to me, anyway) is that the contents of the stringstream are vanishing halfway through the function, and I've no idea why.
You'll see a for-loop in the method. Just before the start of this loop, and then just before the end, are two cout statements. Each prints the contents of the stringstream at its respective time. Before the loop there is a number (the map key) and a bunch of empty space characters in the stream. By the time the second cout statement is printed, the number and the spaces have gone completely (when really they should be found at the start of the string).
I showed this to my tutor and he was similarly baffled. Anybody have a clue what's happening?
string Catalog::catalogItemToString(int itemNumber)
{
int columnWidths[] = {COLUMN_1_WIDTH, COLUMN_2_WIDTH, COLUMN_3_WIDTH, COLUMN_4_WIDTH, COLUMN_5_WIDTH};
//these are the widths of each column in the display, to keep everything neat and orderly.
stringstream sstream;
sstream << itemNumber;
sstream.str(addSpaces(sstream.str(), COLUMN_1_WIDTH)); //addSpaces() simply adds a sufficient number
//of empty space characters to fill out the column
sstream.clear();
map<int, Product *>::iterator it = catalog.find(itemNumber);
vector<string> itemStrings = it->second->toString();
cout << sstream.str() << endl; //AT THIS POINT IT STILL HAS THE PRODUCT
//NUMBER IN THE STRINGSTREAM
for(int index = 0; index < itemStrings.size(); index++)
{
sstream << addSpaces(itemStrings[index], columnWidths[index + 1]);
cout << sstream.str() << endl; //AT THIS POINT THE PRODUCT NUMBER HAS DISAPPEARED FROM THE STREAM.
//HOWEVER, SUBSEQUENT LOOPS WILL APPEND STRINGS FROM THE VECTOR AS EXPECTED
}
return sstream.str();
}