C++ 使用函数在cin和ifstream之间切换
我试图在标准cin、cout和ifstream、ostream之间切换时操作一个具有函数的数组 具体来说,我有一系列书籍,我有一些基本功能,如搜索标题、出版商、价格等。我还有两个函数,分别称为登录和注销,用于在登录时打开文件并将bookList的istream和ostream重定向到该输出文件,以及在注销时关闭并返回istream和ostreamC++ 使用函数在cin和ifstream之间切换,c++,ifstream,istream,C++,Ifstream,Istream,我试图在标准cin、cout和ifstream、ostream之间切换时操作一个具有函数的数组 具体来说,我有一系列书籍,我有一些基本功能,如搜索标题、出版商、价格等。我还有两个函数,分别称为登录和注销,用于在登录时打开文件并将bookList的istream和ostream重定向到该输出文件,以及在注销时关闭并返回istream和ostream void bookList(istream& in, ostream& out) { //ask for command fr
void bookList(istream& in, ostream& out)
{
//ask for command from istream in
//command selection loop
}
int load(ofstream& out, book booklist[], int size)
{
//load list of books from input file
}
void logon(ofstream& out, string filename)
{
out.open(filename.c_str());
}
void logoff(ofstream& out, string filename)
{
out.close();
}
// some other functions
我还需要在注销时在屏幕上或登录时在文件上打印通知给用户,无论何时调用函数
我尝试将ifstream&作为每个函数中的一个参数,但它们只打印到文本文件,而不是在屏幕上,因为它只是ifstream,而不是istream,但以另一种方式执行则不起作用
我的问题是,有没有一种方法可以让函数logon将bookList的istream重定向到ifstream,再重定向到outputfile,反之亦然,以便注销?而不是文件打开状态。这可能不是您想要的,但可以修改
/// this buffer will be used to switch output
void IO_Switch(streambuf* buffer);
int main(){
streambuf *buffer
ofstream fout;
fout.open("filename.txt");
// below you call cout.rdbuf() which directs stream to cout
IO_Switch(cout.rdbuf());
cout << "This is coming to the console";
// below you call fout.rdbuf());
IO_Switch(fout.rdbuf());
cout << "I used cout here, but the stream is redirected to fout ("filename.txt")
return 0;
}
void IO_Switch(streambuf* buffer){
cout.rdbuf(buffer);
}
cout和ofstream都是奥斯特雷姆。cin和ifstream都是istream。这就是你想传递给重载操作符的东西。你应该使用向量,而不是数组,只是为了把那个部分弄清楚。此外,ofstream也是一个ostream,如果没有在函数签名中显式指定f,则可以传递任何ostream或istream。