0
// 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?

cola
  • 12,198
  • 36
  • 105
  • 165
  • 1
    This statement modifies `std::cin`'s state but there are no more IO actions with `std::cin` after it so it has no observable effects/. – bipll Sep 07 '19 at 03:32
  • `*std::cin.tie() << "This is inserted into the file2";` if I add this line before ofs.close(); it still prints on console window, not in file. Why is this? – cola Sep 07 '19 at 03:50
  • @shibly because `std::cin.tie (prevstr)` restores the previously tied ostream, which was `std::cout` – Remy Lebeau Sep 07 '19 at 05:19

1 Answers1

1

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 to stdout because std::cin.tie(prevstr) ties std::cin back to std::cout. prevstr points to the stream that std::cin was tied to before you set it to ofs, which is std::cout. If that line wasn't there it would have printed to the file.

eesiraed
  • 4,626
  • 4
  • 16
  • 34