Solved

PROBLEM: conditional initialisation of stream

Posted on 1997-05-03
2
194 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
ID: 1163255
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
ID: 1163256
Thanks. You've helped a lot. Bruce
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Templates For Beginners Or How To Encourage The Compiler To Work For You Introduction This tutorial is targeted at the reader who is, perhaps, familiar with the basics of C++ but would prefer a little slower introduction to the more ad…
Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

828 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