使用函数在cin和ifstream之间切换

switching between cin and ifstream using a function

本文关键字:ifstream 之间 cin 函数      更新时间:2023-10-16

我试图在标准cin、cout和ifstream、ostream之间切换时,用函数操作数组。

具体来说,我有一组书,我有一些基本功能,如搜索标题、出版商、价格等。我还有两个名为"登录"answers"注销"的功能来打开文件,登录时bookList的istream和ostream重定向到该输出文件,注销时关闭并返回istream、ostream。

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);
}