PROBLEM: conditional initialisation of stream

I have just spent a frustrating time sorting sorting out a problem that occurred in the following structure.....

#include <everything that's needed>
ostrstream  os      ;

... snip

if (condition)  ostrstream os (buf, 100, ios::out)      ;

... snip

if (condition) os << "text string"      ;


What I found is that even with condition true, no data was written to the stream.  When I took the ostrstream initialisation outside the conditional, it worked fine.

Appreciate that this may be judged a platform dependent query, but my first question is: does the initialisation of a stream inside a conditional violate any fundamental rule of C++? No (BC3.1) compiler errors or warnings were issued. My reference (Stroustrup) seems not to refer to the situation.

Who is Participating?
yonatConnect With a Mentor Commented:
You declared *two* streams, both named "os": one as a global
variable, and the other local to main(). In main(), the local os
hides the global variable os. Your "text string" is writen to
the local os.
What you need to do instead of
    if (condintion) ostrstream os(buf, 100, ios::out) ;
    if (condition) os.rdbuf().setbuf(buf, 100);
which attaches buf to the streambuf object contained by os.

Hope this helps.
bevAuthor Commented:
Thanks. You've helped a lot. Bruce
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.