简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM