从结构上写入文件时,额外的魅力

Extra chararcters when writing to a file from a struct

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

我有一个类单元。该类的对象具有名称,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;
}