打印到c++中的文件
Print to file in c++
我必须将一些对象字段打印到文件中。我重载了operator<<
,我有一个使用它的方法"draw
"。
如何将其打印到文件中?
ostream& operator <<(ostream& out, const Widget& obj)
{
int* colors2 = new int[3];
colors2 = obj.getbackgroundColor().getColor();
int* colors = new int[3];
colors = obj.getTextColor().getColor();
out << "[position (" << obj.getPosition().getX() << ","
<< obj.getPosition().getY() << ") ,";
out << "width (" << obj.getWidth() << ") ";
out << "height (" << obj.getHeight() << ") ,";
out << "text (" << obj.getText() << ") ,";
out << "colors (" << colors[0] << "," << colors[1] << "," << colors[2]
<< ") ,";
out << "background colors(" << colors2[0] << "," << colors2[1] << ","
<< colors2[2] << ") ,";
delete[] colors;
delete[] colors2;
return out;
}
您可能希望使用流(输出文件流)的C++。您需要创建一个ofstream对象,打开要写入的文件,然后可以使用默认的<lt;已经为输出文件流定义了运算符,以便打印到文件。
看看ofstream
的C++文档;这将帮助您更好地了解文件I/O。
由于operator<<()
过载,请使用它:
std::ofstream my_file("data.s");
Widget w;
my_file << w;
实现这一点的简单方法:
void draw(const std::string & filename)
{
std::ofstream file(filename.c_str()); //open a file for writing.
//Can use filename directly on newer compilers
file << wiget1; //use the << operator overload
file << wiget2;
...
}
上述版本将为每次调用draw
打开、覆盖和关闭filename
。如果您计划在同一文件中多次调用draw
和所有这些draw
的输出,这可能不是您想要的。
您可以在其他位置打开file
并将其传递给draw
,而不是传入文件名并打开file
。这将允许对同一文件多次调用draw
。
其他地方:
std::ofstream file(filename.c_str());
新绘图:
void draw(std::ofstream & file)
{
file << wiget1; //use the << operator overload
file << wiget2;
...
}
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 文本文件中的单词链表
- CMake-按正确顺序将项目与C运行时对象文件链接
- 使用新行和不使用新行读取文件
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 挂起和取消挂起一个文件DLL
- 如何确定我已使用非编码文件到达 EOF?
- 命名空间中具有.h和.cpp文件的类
- 如何使用ndk-build.cmd构建Android.so文件
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 读取文件并输入到矢量中
- 在C++中查找文件
- c++库的公共头文件中应该包含什么
- 用c++从输入文件中读取另一行
- Cppcheck生成xml转储文件
- 读取文件的最后一行并输入到链接列表时出错
- 无法编译 rtmidi 测试 cmidiin.cpp 文件, 非法指令
- 如何将内容数组写入文本文件?
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到