我必须编写一个“登录”和一个“注销”函数,将当前 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/