Solved

PROBLEM: conditional initialisation of stream

Posted on 1997-05-03
2
188 Views
Last Modified: 2010-04-10
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      ;

main()
{
... snip

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

... snip

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

...snip...
}

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.

0
Comment
Question by:bev
2 Comments
 
LVL 5

Accepted Solution

by:
yonat earned 25 total points
Comment Utility
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) ;
is
    if (condition) os.rdbuf().setbuf(buf, 100);
which attaches buf to the streambuf object contained by os.

Hope this helps.
0
 

Author Comment

by:bev
Comment Utility
Thanks. You've helped a lot. Bruce
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now