c++ - 将 ofstream 分配给 ostream

标签 c++ iostream fstream assign

我必须编写一个“登录”和一个“注销”函数,将当前 iostream 从函数重定向到 fstream 并返回。

更具体地说,我有:

void console (istream& in, ostream& out)
{
    //take command from user through console
    //default input/ output stream is in/out
}

void logon (ostream& out, string filename)
{
    ofstream fileout;
    fileout.open(filename);
    //assign this fstream fileout to ostream& out
}

void logoff (ostream& out)
{
    // take current ofstream fileout
    fileout.close();
    // return the stream back to out
}

程序应该像这样工作:

  • 用户输入一些命令:输出到控制台
  • 用户输入登录文件名命令:创建一个文件并将输出重定向到该文件
  • 用户输入一些命令:输出到文件
  • 用户输入注销:关闭文件,将输出重定向回控制台 我知道 ofstream 是 ostream 的一部分,但不知道如何在两者之间进行操作。 请提供帮助,我们将不胜感激。

最佳答案

你也可以使用 std::string 作为中介:

void consoleIn (std::istream& in, std::string& strInput)
{
in >> strInput;
}

void logon (std::ostream& out, std::string filename, std::string const& MyText)
{
std::ofstream fileout;
fileout.open(filename);
fileout << MyText;
}

顺便说一下,尝试使用 std::来指定标准对象。

关于c++ - 将 ofstream 分配给 ostream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29225355/

相关文章:

c++ - 如何让日志更容易维护?

c++ - 无法遍历 STL 集

c++ - 未输入 If-block,不知道为什么

c++ - 我需要在写入后和读取前关闭文件吗?

c++ - try catch 语法构造函数

c++ - 如何使用 boost::gil 处理数字像素操作中的溢出?

c++ - 如何在 CppUnit 中漂亮地打印 STL 数据结构?

c++ - 为什么 std::cout 而不是简单的 cout?

c++ - 允许用户输入空格?

c++从文件中读取加倍,但如果程序遇到字符串则记录