cola
cola

Reputation: 12486

Can anyone explain the code about cin.tie() in C++?

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

Upvotes: 0

Views: 316

Answers (1)

eesiraed
eesiraed

Reputation: 4654

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.

Upvotes: 1

Related Questions