The std::[io]fstreams
in
and out
have local scope (or automatic storage duration) inside the TestWithStdIO
constructor. They are destroyed (and the files closed), along with their contained buffers, at the end of the function, leaving you with dangling pointers insidecin
and cout
.
Consider instead making in
and out
members of TestWithStdIO
, something like this:
class TestWithStdIO {
std::streambuf* cinbuf;
std::streambuf* coutbuf;
std::ifstream in_; // <-- member
std::ofstream out_; // <-- member
public:
TestWithStdIO(const std::string& inFile, const std::string& outFile) :
in_(inFile), out_(outFile) // <-- initializer list
{
cinbuf = std::cin.rdbuf();
std::cin.rdbuf(in_.rdbuf());
coutbuf = std::cout.rdbuf();
std::cout.rdbuf(out_.rdbuf());
}
~TestWithStdIO() {
std::cin.rdbuf(cinbuf);
std::cout.rdbuf(coutbuf);
}
};
You might need in(inFile.c_str())
and the equivalent for out
if you only have C++03
support.
Also, as pointed out in the comments, there is no need to dynamically allocate the TestWithStdIO
instance, and in fact it is likely to be a source of bugs. Just do
TestWithStdIO ioTest ("in.txt", "out.txt");