将结构中的信息写入文件

时间:2014-04-23 01:40:43

标签: c++

好吧所以我有这两个结构,我把它们发送到一个函数保存到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;
}
}

2 个答案:

答案 0 :(得分:1)

如果你想要一个像你在问题中写的那样的解决方案,你需要做的就是在你写出的每个属性之后放置和结束。

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

只要您尝试输出的信息是文件中的所有信息,这应该有效。

然后你可以按照你编写的顺序读回来。在回读可能包含空格的字符串时要小心。

答案 1 :(得分:0)

您需要为已定义的类 Cost Creatures 编写重载运算符&lt;&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 FAQ链接

http://isocpp.org/wiki/faq/input-output#output-operator