【问题标题】:switching between cin and ifstream using a function使用函数在 cin 和 ifstream 之间切换
【发布时间】:2015-05-21 17:51:07
【问题描述】:

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

具体来说,我有一系列书籍,我有一些基本功能,如搜索标题、出版商、价格等。我还有两个名为“登录”和“注销”的函数来打开文件和 重定向 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),但以另一种方式进行是行不通的。

我的问题是,是否有方法可以使功能登录将 bookList 的 istream 重定向到 ifstream 到输出文件,反之亦然以进行注销?而不是“文件打开”条件。

【问题讨论】:

  • coutofstream 都是 ostreamcinifstream 都是 istream。这就是你想要传递的(想想重载operator<<operator>>)。
  • 您应该使用vector<book>,而不是数组,只是为了让那部分变得直截了当。此外,ofstream 也是 ostream,如果您没有在函数签名中明确指定“f”,则可以将其传递给任何 ostreamistream

标签: c++ ifstream istream


【解决方案1】:

这可能不是您想要的,但可以修改。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多