How do I use the ostringstream properly in c++?

2020-07-02 11:44发布

问题:

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.

回答1:

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();
}