打印到c++中的文件

Print to file in c++

本文关键字:文件 c++ 打印      更新时间:2023-10-16

我必须将一些对象字段打印到文件中。我重载了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; 
    ...
}