Re: A beginner's string/ostream question
On Wed, 06 Feb 2013 01:09:46 -0600, James Moe wrote:
Hello,
I thought to replace some C code with equivalent C++ for formatting
text to output; the code is inside of a processing loop. My C++ attempt
usually ends with an empty string.
Where have I gone awry?
<snip>
----[ C++ attempt to emulate it ]----
string msg1, msg2;
std::ostringstream stro(msg1);
Your failure is in misunderstanding what the line above does.
It does *not* create a stream that uses msg1 as its buffer. Instead, it
creates a stream that starts out with the same contents as msg1 has.
msg2 = string(" messages in [") +
string(foldname) +
string("]");
if ((0 == nmsgs2) || (nmsgs2 < nmsgs1))
stro << " Reindexed " << std::setw(4) << nmsgs1 << msg2;
else
stro << " Reindexed " << std::setw(4) << nmsgs1
<< " of " << std::setw(4) << nmsgs2
<< "(" << std::setw(3) << ((nmsgs1 * 100) / nmsgs2) << "%)" <<
msg2;
To get the stream contents into msg1, you need
msg1 = stro.str();
here.
I would have written this code as
std::ostringstream stro;
if ((0 == nmsgs2) || (nmsgs2 < nmsgs1))
{
stro << " Reindexed " << std::setw(4) << nmsgs1;
}
else
{
stro << " Reindexed " << std::setw(4) << nmsgs1
<< " of " << std::setw(4) << nmsgs2
<< " (" << std::setw(3) << ((nmsgs1*100)/nmsgs2) << "%)";
}
stro << " messages in [" << foldname << "]";
std::string msg1 = stro.str();
The main difference is that I also build the second part in the stream,
instead of using string concatenation and pushing that result into the
stream.
Bart v Ingen Schenau
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]