Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/148.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 将流分配给ostream_C++_Iostream_Fstream_Assign - Fatal编程技术网

C++ 将流分配给ostream

C++ 将流分配给ostream,c++,iostream,fstream,assign,C++,Iostream,Fstream,Assign,我必须编写一个“logon”和一个“logoff”函数,将当前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, strin

我必须编写一个“logon”和一个“logoff”函数,将当前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的一部分,但不知道如何在两者之间进行操作。 请帮忙,任何意见都将不胜感激

能否使用字符串流作为中介

stringstream ss;
while ofstream has data
    ofstream >> ss
    ostream << ss
....
stringstreamss;
而流有数据
流>>ss

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;
}
void控制台输入(std::istream&in,std::string&strInput)
{
在>>strInput中;
}
无效登录(std::ostream&out、std::string filename、std::string const&MyText)
{
std::流文件输出;
打开(文件名);

fileout我想做一些类似的事情。我有一个输出到std::cout的日志模块,但我希望使用库的程序能够指定改为登录到文件。但是,当我的程序创建std:;ostream并将其传递给我的模块时,我的模块无法存储它。