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

编程入门 行业动态 更新时间:2024-10-27 22:32:20
本文介绍了如何在C ++中正确使用ostringstream?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

当我的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?

本文发布于:2023-11-15 01:52:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1590091.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:正确   如何在   ostringstream

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!