开发者

Need help/advice on how to test an ostream passed to a function

I have a function that gets an ostream passed to it. I need to test the ostream to make sure it will work. I put the print statement in a try block with a catch statement to catch all exceptions. Now to test if this will work, i need a little help creating a bad ostream to pass the function.

I tried this:

filebuf buffer;
ostream& out = ostream(&buffer);
test1.print(out);

But when i test it, i cannot get my error message to be printed. What would be a better way to 开发者_Go百科create a bad ostream to be passed to the function.

Also, is there a better way to check the ostream than using a try-catch block?


How about an ofstream that's not open to any file?


Streams don't in general throw exceptions when they don't work, so I would not expect your error message to be printed whether your operation succeeded or not.

The ios base class has a function called exceptions that can be used to control that, but it's fairly anti-social to write a function that changes the state of an argument like that, so you might have to be sure to restore it (even if it throws an exception...)

The usual way to test success of an operation on a stream is using if. A stream evaluates to a true value if everything is OK, a false value otherwise - by which I mean a value that's true/false as far as conditionals are concerned, not the bool values true or false.

To be precise, it's false if the failbit or badbit is set. The last operation "didn't work" if and only if at least one of those is set.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜