将结构中的信息写入文件
Writing information in a structure to a file
好吧,我有这两个结构,我把它们发送到一个函数中,保存到一个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-操作员
相关文章:
- 如何修复函数中的 fstream 文件输入以将正确的信息存储在结构数组中?
- 创建进行生产构建并创建调试信息的C++生成文件的最佳方法?
- 将对象信息保存到二进制文件中
- 错误 VSP1011:无法获取调试信息.与 /配置文件链接器开关链接
- Qt读取文本文件的一些信息
- 将文件信息(字符数组)嵌入到编译的二进制文件中
- 从带有 getline() 的文件读入一行上有多个信息得到无效参数错误
- 如何使用所有其他文件信息来编译代码,例如HAAR级联训练的权重的XML文件
- 是否可以将信息从XML文件转换为CPP
- 如何在文本文件中搜索员工记录(按名称)并仅显示其详细信息?
- CVE解析文件信息
- C++Pig拉丁代码,只删除文件信息
- 如何在Linux终端的目录下显示详细的文件信息?-C++
- CaptureStackBackTrace和文件信息
- 如何在 Linux 中获取当前目录下的文件信息
- 如何获取文件信息
- 损坏的配置文件信息与g++和CMake
- fscanf,逗号文本文件信息字符串和数字
- 添加资源.Rc文件信息项目
- 在用c++或c#打开文件之前检测文件信息