Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 507
Arminium Avatar asked Sep 02 '12 05:09

Arminium


People also ask

What is CPP Ostringstream?

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 .

Is Ostringstream an Ostream?

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".


1 Answers

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();
}
like image 108
André Oriani Avatar answered Oct 04 '22 06:10

André Oriani