将结构中的信息写入文件

Writing information in a structure to a file

本文关键字:文件 信息 结构      更新时间:2023-10-16

好吧,我有这两个结构,我把它们发送到一个函数中,保存到一个txt文件中。

struct Cost
    {
        double hours;
        double cost;
        double costFood;
        double costSupplies;
    };
struct Creatures
{
    char name[50];
    char description[200];
    double length;
    double height;
    char location[100];
    bool dangerous;
    Cost management;
};

这是我困惑的函数的一部分,我不知道如何把这个结构的每一行都写到文件中。有人能给我解释一下怎么做吗?

file.open(fileName, ios::out);
if (!file)
{
    cout << fileName << " could not be opened." << endl << endl;
}
else
{
    fileName << c.name
            << c.description
            << c.lenght
            << c.height
            << c.location
            << c.dangerious
            << c.management.hours
            << c.management.cost
            << c.management.costFood
            << c.management.costSupplies;
            file.close();
    cout << "Your creatures where successfully save to the " << fileName << " file." << endl << endl
        << "GOODBYE!" << endl << endl;
}
}

如果你想要一个像你在问题中写的那样的解决方案,你所需要做的就是在你写的每个属性后面加上结束行。

fileName << c.name << std::endl
<< c.description << std::endl
...

只要你试图输出的信息是文件中的全部内容,这就应该有效。

然后你可以按照你写的顺序把它们读回来。只要在回读字符串时要小心,因为字符串中可能有空格。

您需要编写重载运算符<lt为您定义的类成本生物

class Cost {
public:
friend std::ostream& operator<< (std::ostream& o, const Cost& c);
// ...
private:
// data member of Cost class
};
std::ostream& operator<< (std::ostream& o, const Cost& c)
{
return o << c.hours<<"t"<<c.cost<<"t"<<c.costFood<<"t"<<c.costSupplies<<std""endl;
}

现在您可以按如下方式使用它:

Cost c;
std::cout<<c<<"n";

有关此概念的详细信息,您可以参考此上的ISOCPP常见问题链接

http://isocpp.org/wiki/faq/input-output#output-操作员