简体   繁体   English

如何在c ++中正确使用ostringstream?

[英]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. 当我调用toString()方法时,我试图返回一些信息,包括一个整数和一些浮点数。 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. 我了解到ostringstream工作得很好,但是当一遍又一遍地调用包含这个方法的类时,信息会堆叠到我之前的输出上。 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" “产品名称:电影票单位:49价格:9.99收入:9.99美元”

"Product name: Movie Ticket Units left: 4926 Price: 9.999.99 Revenue: $9.99239.76" “产品名称:电影票单位:4926价格:9.999.99收入:$ 9.99239.76”

where the second one should display 第二个应该显示的位置

"Product name: Movie Ticket Units left: 26 Price: 9.99 Revenue: $239.76" “产品名称:电影票单位:26价格:9.99收入:$ 239.76”

I know it's just a matter of updating, but that's where I'm lost. 我知道这只是一个更新的问题,但那就是我迷失的地方。

Declare int_buffer , float_buffer , and float_buffer2 inside toString() function. toString()函数内声明int_bufferfloat_bufferfloat_buffer2 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. 因为你在类中声明,所以这些对象被保留,所以每次调用toString()函数时,你float_buffer连接到int_bufferfloat_bufferfloat_buffer2 If you declare inside the method they will exist only while the toString is active. 如果在方法内部声明它们将仅在toString处于活动状态时存在。 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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM