使用函数在cin和ifstream之间切换
switching between cin and ifstream using a function
我试图在标准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);
}
相关文章:
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- int(c) 和 c-'0' 之间的区别。C++
- ifstream什么都没读
- 在cuda线程之间共享大量常量数据
- 在c代码之间共享数据的最佳方式
- Mix_Init和Mix_OpenAudio SDL之间的区别是什么
- C++ 使用 assign 函数的字符串与直接使用 '=' 更改值的字符串之间的区别
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- std::atomic和std::condition_variable wait,notify_*方法之间的区别
- 大小相等但成员数量不同的结构之间的性能差异
- 类与私有变量的其他类之间的线程安全性
- 如何在cpp文件之间切换窗口?在Qt中
- 线程之间的布尔停止信号
- 我是C++编程的新手,这些代码之间有什么区别,我应该使用哪一个
- ifstream 尝试读取 9 到 13 之间的无符号字符时非常奇怪的行为
- 使用函数在cin和ifstream之间切换
- C++在同一对象的成员之间传递 ifstream 变量
- 尝试在std::cout和std::ifstream之间切换
- 将ifstream强制转换为bool和使用ifstream::is_open()之间的区别
- ifstream打开由cin命名的文件,但从数组中提取时不打开.cin和常规字符串定义之间的任何区别