如何在 C++ 中正确使用 ostringstream?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12233710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I use the ostringstream properly in c++?
提问by Arminium
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
我试图在调用 toString() 方法时返回一些信息,其中包括一个整数和一些浮点数。我了解到 ostringstream 工作得很好,但是当包含此方法的类被一遍又一遍地调用时,信息会堆积在我之前的输出中。这是我的代码
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.
我知道这只是更新的问题,但这就是我迷失的地方。
回答by André Oriani
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:
声明int_buffer
、float_buffer
和float_buffer2
内部toString()
函数。因为你是在类的声明,这些对象保持周围,所以每次通话时间toString()
的功能你要串联int_buffer
,float_buffer
以及float_buffer2
一遍又一遍。如果您在方法内部声明它们将仅在toString
活动时存在。无论如何,你正在为你想要做的事情做太多的代码。你可以简单地做:
std::string toString()
{
std::ostringstream buffer;
buffer << "Product name: "<< description << " Units left: " << on_hand << " Price: "<< price << " Revenue: $" << generated_revenue;
return buffer.str();
}