关于c++中的流
regarding streams in c++
我想使用文件流和控制台输出流。在构造函数中,我希望根据传递给构造函数的参数使用文件或控制台输出流进行初始化。然后我将在类中有另一个函数,它将输出重定向到该流。它的代码是什么?我正在尝试下面的代码是不工作。欢迎提出其他设计建议。
class Test
{
private:
std::ios *obj;
std::ofstream file;
std::ostream cout1;
public:
// Test(){}
Test(char choice[])
{
if(choice=="file")
{
obj=new ofstream();
obj->open("temp.txt");
}
else
obj=new ostream();
}
void printarray()
{
for(int i=0;i<5;i++)
(*obj)<<"n n"<<"HI"
}
};
应该这样做:
#include <iostream>
#include <fstream>
#include <string>
class Test
{
private:
std::ofstream file;
std::ostream& obj;
public:
// Use overloaded constructors. When the default constructor is used,
// use std::cout. When the constructor with string is used, use the argument
// as the file to write to.
Test() : obj(std::cout) {}
Test(std::string const& f) : file(f.c_str()), obj(file) {}
void printarray()
{
for(int i=0;i<5;i++)
obj<<"n " << "HI" << " n";
}
};
int main()
{
Test a;
a.printarray();
Test b("out.txt");
b.printarray();
}
PS看printarray
的变化。你所尝试的,与%s
,是好的printf
族的函数,但不是std::ostream
。
欢迎提出其他设计建议。
其中两个成员是无用的:
std::ios *obj;
std::ofstream file;
std::ostream cout1;
你不能用std::ios
做任何事情,没有与streambuf
关联的std::ostream
是无用的,你永远不会使用file
或cout1
!
你想:
std::ofstream file;
std::ostream& out;
如R Sahu的回答所示,并写信给out
。
Test(char choice[])
{
if(choice=="file")
这不起作用,您需要使用strcmp
来比较char
字符串。你应该使用std::string
而不是char*
。
相关文章:
- 一个关于在C++中重载布尔运算符的问题
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 关于std::move的使用,是否有编译警告
- 关于简单C++函数(is_palindrome)的逻辑的问题
- 如何处理来自核心指南检查器的关于gsl::at的静态分析警告
- 关于:C++中异常对象的范围:为什么我没有得到副本?
- 关于C++中具有多重继承"this"指针的说明
- 关于 c++ 函数中指针赋值的简单问题
- 关于 std::min, std::max 中的比较运算符的混淆
- 这是关于成员访问规则的正确摘要吗
- C++ 关于指针取消引用的技术问题
- std::is_trivially_copyable_v 关于虚拟功能
- 关于指向指针数组的指针
- 关于复制构造函数的一个棘手问题
- 我已经阅读了很多关于 2d 数组的信息,但我在作业中使用它时遇到了麻烦
- 关于类的 Python 文档 - 对C++的引用不正确
- 关于 C++ 中的函数类型定义
- 关于条件块的问题与&&运算符有关
- 关于如何使用指向主窗口的指针的 QT 问题
- [temp.variadic]中关于包扩展实例化的措辞