// redefine tied object
#include <iostream> // std::ostream, std::cout, std::cin
#include <fstream> // std::ofstream
int main () {
std::ostream *prevstr;
std::ofstream ofs;
ofs.open ("test.txt");
std::cout << "tie example:\n";
*std::cin.tie() << "This is inserted into cout";
prevstr = std::cin.tie (&ofs);
*std::cin.tie() << "This is inserted into the file";
std::cin.tie (prevstr);
ofs.close();
return 0;
}
We can get same output if we remove the line:
std::cin.tie (prevstr);
Why is this?
std::cin.tie(prevstr)doesn't do anything in your original code because you didn't perform any operations on the stream afterward.*std::cin.tie() << "This is inserted into the file2"prints tostdoutbecausestd::cin.tie(prevstr)tiesstd::cinback tostd::cout.prevstrpoints to the stream thatstd::cinwas tied to before you set it toofs, which isstd::cout. If that line wasn't there it would have printed to the file.