I am attempting to return some information when my toString() method is called, which include an integer and some floats. I learned about ostringstream works great but when the class that contains this method is called over and over again, the information gets stacked onto my previous output. Here is my code
ostringstream int_buffer, float_buffer, float_buffer2;
is introduced at the beginning of my class, then
string toString()
{
int_buffer << on_hand;
float_buffer << price;
float_buffer2 << generated_revenue;
string stron_hand = int_buffer.str();
string strprice = float_buffer.str();
string strrev = float_buffer2.str();
string output = "Product name: " + description + " Units left: " + stron_hand + " Price: " + strprice + " Revenue: $" + strrev;
return output;
}
I know my coding is awful, I'm still fairly new to this, but an example of my output is,
"Product name: Movie Ticket Units left: 49 Price: 9.99 Revenue: $9.99"
"Product name: Movie Ticket Units left: 4926 Price: 9.999.99 Revenue: $9.99239.76"
where the second one should display
"Product name: Movie Ticket Units left: 26 Price: 9.99 Revenue: $239.76"
I know it's just a matter of updating, but that's where I'm lost.
std::ostringstreamOutput stream class to operate on strings. Objects of this class use a string buffer that contains a sequence of characters. This sequence of characters can be accessed directly as a string object, using member str .
ostringstream is used when you need stream stuff into string , whereas ostream is mostly used as a type for a parameter (referenced) when the callee is stream implementation agnostic. And "ostream objects are stream objects used to write and format output as sequences of characters".
Declare int_buffer
, float_buffer
, and float_buffer2
inside toString()
function. Because you are declaring in the class, those objects are kept around, so every time you call toString()
function you are concatenating to int_buffer
, float_buffer
, and float_buffer2
over and over. If you declare inside the method they will exist only while the toString
is active. Anyway, you are doing too much code for what you are trying to do. You could simply do:
std::string toString()
{
std::ostringstream buffer;
buffer << "Product name: "<< description << " Units left: " << on_hand << " Price: "<< price << " Revenue: $" << generated_revenue;
return buffer.str();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With