简体   繁体   English

使用功能在cin和ifstream之间切换

[英]switching between cin and ifstream using a function

I am trying to manipulate an array with functions while switching between standard cin, cout and ifstream,ostream. 我试图在标准cin,cout和ifstream,ostream之间切换时使用函数操作数组。

Specifically, I have an array of books and I have some basic functions like search title, publisher, price, etc. I also have 2 functions called "login" and "logout" to open a file and redirect bookList's istream and ostream to that outputfile when login, as well as close it and return back to istream, ostream when logout. 具体来说,我有一系列的书,并且有一些基本功能,例如搜索标题,出版商,价格等。我还有两个函数,分别称为“登录”和“注销”,以打开文件并将 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

I also need to print out notification to the user (either onscreen when logged off or on file when logged on) whenever a function is called. 每当调用函数时,我还需要向用户打印通知(注销时显示在屏幕上或登录时显示在文件上)。

My tried to put ifstream& as a parameter in each functions, but they only print out to text file not on screen (because its just ifstream, not istream), but doing it the other way won't work. 我试图在每个函数中将ifstream&作为参数,但是它们只打印到文本文件而不显示在屏幕上(因为它只是ifstream,而不是istream),但以其他方式不能工作。

My question is that is there method that can make function logon redirect istream of bookList to ifstream to the outputfile and vice versa for logoff? 我的问题是,有没有方法可以使函数登录将bookList的istream重定向到ifstream到输出文件,反之亦然以注销? Rather than a "is-file-open" condition. 而不是“正在打开文件”条件。

This may not be directly what your looking for but can be modified. 这可能不是您要查找的直接内容,但可以对其进行修改。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM