当我的toString()方法被调用时,我试图返回一些信息,其中包括一个整数和一些浮点数.我了解到ostringstream的工作原理很好,但是当一遍又一遍地调用包含此方法的类时,该信息将堆积到我的先前输出中.这是我的代码
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,
产品名称:电影票剩余数量:49个价格:9.99收入:9.99美元"
"Product name: Movie Ticket Units left: 49 Price: 9.99 Revenue: $9.99"
产品名称:电影票剩余数量:4926价格:9.999.99收入:$ 9.99239.76"
"Product name: Movie Ticket Units left: 4926 Price: 9.999.99 Revenue: $9.99239.76"
第二个应显示的位置
产品名称:电影票剩余数量:26价格:9.99收入:$ 239.76"
我知道这只是更新的问题,但这就是我迷路的地方.
I know it's just a matter of updating, but that's where I'm lost.
推荐答案在toString()函数中声明int_buffer,float_buffer和float_buffer2.因为您在类中声明,所以这些对象一直保留着,因此每次调用toString()函数时,都会一遍又一遍地串联到int_buffer,float_buffer和float_buffer2.如果在方法内部声明,则它们仅在toString处于活动状态时存在.无论如何,您正在为要执行的工作做太多的代码.您可以简单地做到:
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(); }更多推荐
如何在C ++中正确使用ostringstream?
发布评论