> Hi all,
>
> Why doesn't the following unmanaged C++ code work as expected:
>
> string s;
> ostringstream strm(s); // This stream should store results in s
Where did you get the idea that the comment above is correct? The above
is just shorthand for:
ostringstream strm;
strm << s;
> strm << 25;
> cout << s << endl; // s still contains an empty string
Right, since you've misunderstood what the ostringstream constructor does.
> cout << strm.str(); // but the stream internally contains "25"
An ostringstream doesn't hold a reference to a string, but rather is
interoperable with strings. You need:
ostringstream strm;
strm << 25;
string s(strm.str());
//etc.
Tom
Bob Altman - 14 Mar 2005 19:24 GMT
> > string s;
> > ostringstream strm(s); // This stream should store results in s
>
> Where did you get the idea that the comment above is correct?
"Beginning C++" by Ivor Horton, 1998 ed., page 802, states (apparently
incorrectly):
You can use an ostringstream object to format data into a string. For
instance, you could create a string object and an output string stream with
the statements:
string outBuffer;
ostringstream outStr(outBuffer);
You can now use the insertion operators to write to outBuffer via outStr:
double number = 2.5;
outStr << "number = " << (number / 2);
As a result of the write to the string stream, outBuffer will contain
"Number = 1.25"... The string parameter to the string stream constructor is
a reference, so write operations for ostringstream objects act directly on
the string object.
Carl Daniel [VC++ MVP] - 14 Mar 2005 20:39 GMT
>>> string s;
>>> ostringstream strm(s); // This stream should store results in s
[quoted text clipped - 3 lines]
> "Beginning C++" by Ivor Horton, 1998 ed., page 802, states (apparently
> incorrectly):
Dump that book and pick up a copy of "Accelerated C++" by Andrew Koenig and
Barbara Moo. It's 1/3 the length, has far more content, and is actually
correct.
-cd