Testing an Overloaded Stream Operator

Hey guys, I'm wondering if there is a way to have access to the buffers used within cout/cin such that I can verify that overloaded stream operators are working correctly. The class I'm working with is a complex number class (CCmplxNum) which has the operators implemented.

std::istream &operator>>(std::istream &s, CCmplxNum &oZ);
std::ostream &operator<<(std::ostream &s, const CCmplxNum &oZ);

To give you an example of what I mean:

CCmplxNum oZ(1,1); // Create a complex num 1+1i
cout << oZ; // Displays complex number, "1+1i"
cin >> oZ; // User inputs a complex number

So I need a way of checking what is displayed to screen, and specifying what input is expected.

My guess is to create a seperate I/O stream (istream/ostream), and read the data that is placed into the ostream by the << operator. And to test the >> operator, place data into the istream, call the >> operator, and then check the oZ was updated correctly. I.e

istream inStream;
ostream outStream;
CCmplxNum oZ(1,1);
string strTest;

outStream << oZ; // Put oZ into the ostream
strTest = outStream.Something?; // ostream doesnt have any accessor methods
if (strTest == "1+1i"); // Testing

strTest = "1+1i"; // Test Input
inStream << strTest; // Somehow put the data into the stream
inStream >> oZ; // Test the extraction operator

The only problem is istream/ostream dont allow reading/writing to them, so you have no way of manipulating their buffers. Could anyone point me in the right direction?

Cheers, TjLusco
So I need a way of checking what is displayed to screen, and specifying what input is expected.


Am I missing something? Why can't you just use cin/cout and see what is put on the screen?


EDIT:

although I suppose if you want to check it programmatically you can use a stringstream:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <sstream>

//...

stringstream test;
test.str("5+3i");

test >> foo;
if( /*check foo here*/ )
  //...

test.str("");
foo = Foo(2,7);
test << foo;

if(test.str() == "2+7i")
  //... 
Last edited on
Thanks! I was unfamiliar with the use of stringstreams so I wasn't sure if they were compatible with normal i/ostream operators. So the compiler will automatically typecast a stringstream to the appropriate istream/ostream as necessary in the operators? Correct me if that is wrong.
stringstreams are both istreams and ostreams, so yes, it will work just fine with your operators.
Topic archived. No new replies allowed.