2014-04-23 82 views
0

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

这是IM功能上混淆的部分,我不知道如何利用这种结构的每一行,并将其写入文件。有人可以向我解释如何做到这一点?

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; 
} 
} 
+0

你将不得不为运算符<<为你的上述两个结构。这样你就可以在你的程序中使用它。 –

+0

编辑为我认为你的意思。 – Baalzamon

回答

0

你需要写重载操作< <为您定义的类成本生物

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"; 

有关此概念的详细信息,您可以参考这个

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

+0

我从来没有见过这样的事情,有没有更简单的方法呢? – Baalzamon

+0

@Baalzamon:这是你需要做的方式。请参考常见问题解答页面,了解关于isotream的概念。您可以使用/运行ISOCPP FAQ中提供的程序开始学习。 –

+0

老实说,甚至不认为我们会覆盖这样的东西,直到下一课的数据结构。我们应该使用Advance文件操作符。比如上面试图做的事情。 – Baalzamon

1

的ISOCPP FAQ链接如果你想像你在你的问题中写的所有你需要做的解决方案是在你写出每个属性之后放置和结束行。

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

只要你试图输出的信息是文件中的所有内容,这应该工作。

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

+0

+1。 K.I.S.S.的完美例子原理。 –