【发布时间】: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 到输出文件,反之亦然以进行注销?而不是“文件打开”条件。
【问题讨论】:
-
cout和ofstream都是ostream。cin和ifstream都是istream。这就是你想要传递的(想想重载operator<<和operator>>)。 -
您应该使用
vector<book>,而不是数组,只是为了让那部分变得直截了当。此外,ofstream也是ostream,如果您没有在函数签名中明确指定“f”,则可以将其传递给任何ostream或istream。