从结构上写入文件时,额外的魅力
Extra chararcters when writing to a file from a struct
我有一个类单元。该类的对象具有名称,ID,预算和其他内容。我想将名称和预算保存在位置(i-1)的.txt文件中。我创建了名为unit2的结构:
struct Unit2{
string name;
int budget;
};
我的file.write函数:
void writeBudgets(Unit name,int i) {
ofstream file("C:\Users\User\Desktop\budgets.txt");
Unit2 p;
p.name = name.getName(); //get name from the class Unit
p.budget = name.getBudget(); //same for budget
file.seekp((i-1)*sizeof(Unit2));
file.write(reinterpret_cast<char*> (&p),sizeof(Unit2));
file.close();
}
在主i创建单位" a"的对象" a" a ass"answers"预算" 120.当我使用writebudgets函数时,添加了额外的字符。例如writeBudgets(a,2);
给我这个hÆPasd ÌÌÌÌÌÌÌÌÌÌÌÌ Œ
。我应该做什么?
您不能将std::string
像这样写入文件,因为std::string
对象本身内部没有实际字符串,而是指向字符串的指针以及其长度。<<<<<<<<<<<</p>
您应该做的是了解有关C 输入/输出库的更多信息,然后您可以为您的结构制作自定义的输出操作员<<
。
您制作自定义operator<<
功能:
std::ostream& operator<<(std::ostream& os, const Unit2& unit)
{
// Write the number
os << unit.budget;
// And finally write the actual string
os << unit.name << 'n';
return os;
}
使用上述功能,您现在可以做,例如
Unit2 myUnit = { "Some Name", 123 };
std::cout << myUnit;
它将在标准输出上打印
123一些名字
要读取结构,您可以制作一个相应的输入运算符函数:
std::istream& operator>>(std::istream& is, Unit2& unit)
{
// Read the number
is >> unit.budget;
// The remainder of the line is the name, use std::getline to read it
std::getline(is, unit.name);
return is;
}
相关文章:
- 在树结构.txt文件中搜索节点
- sizeof 函数如何在带和不带位字段的结构上工作?(填充)
- 未使用的 asm() 在不受支持的体系结构上的行为
- 复制引用结构上的赋值
- 有了memory_order_relaxed,原子变量的总修改顺序如何在典型体系结构上得到保证
- 这些结构在文件中的大小不同,但在程序内存中的大小相同
- C 嵌套结构上的 g++ 编译错误
- 结构上溢出的整数加法
- 在通过 P/Invoke 获取的 C++ 结构上设置 C# 回调
- 在包含浮点数的结构上使用 memset()
- 读取结构化文件
- 如何使用write()函数将结构写入文件
- 在模板化数据结构上调用 begin() 或 end()
- 将结构写入文件
- 在现有数据结构上使用BGL算法需要什么(边和顶点作为矢量<对象*>)?
- boost :: Spirit :: Karma语法:逗号从结构上划定了带有选件属性的输出
- 使用提升库在队列和堆栈数据结构上保存和加载数据时出错
- 所有结构上的奇怪内存位移
- 从结构上写入文件时,额外的魅力
- C++在结构上使用指针并将其保存在文件中