c++ - 从文件 C++ 访问对象时出现读取访问冲突。

标签 c++ c++11

在下面的类中,错误出现在 init 函数中,我将存储在文件中的类对象加载到 vector Items。

class Item
{
std::string item_code;
std::string item_name;
std::string unit_name;
unsigned int price_per_unit;
double discount_rate;
static std::vector<Item> Items;
friend std::ostream& operator<< (std::ostream&, Item&);

public:
static void PrintAll();
static void Init();
~Item();
};

默认构造函数是从用户读取数据并写入文件的构造函数。下面是默认构造函数的代码。

Item::Item(int a)
{
std::cout << "Item name : ";
std::getline(std::cin, item_name);
std::cout << "Unit (Kg/g/Qty) : ";
std::getline(std::cin, unit_name);
std::cout << "Price per unit : ";
std::cin >> price_per_unit;
std::cout << "Discount Rate : ";
std::cin >> discount_rate;
std::cin.ignore();
std::cout << "Product code (has to be unique) : ";
std::getline(std::cin, item_code);

std::ofstream outfile;
outfile.open("Files\\Items.txt", std::ios::out | std::ios::app);
outfile.write((char*)&(*this), sizeof(Item));
outfile.close();
}

下面是引发读取访问冲突的 Init() 函数。

void Item::Init()
{
std::ifstream infile("Files\\Items.txt", std::ios::in);
if (!infile.is_open())
{
    std::cout << "Cannot Open File \n";
    infile.close();
    return;
}
else
{
    Item temp;
    while (!infile.eof())
    {
        infile.read((char*)&temp, sizeof(temp));
        Item::Items.push_back(temp);
    }
}
infile.close();
}

即使我正在检查 eof,也会抛出读取访问冲突。请就此问题给我一些建议。

最佳答案

    infile.read((char*)&temp, sizeof(temp));

这会用文件中的垃圾填充 temp 对象。它应该包含有效的 std::string 对象和文件中的任何内容,它不可能是有效的 std::string 对象。如果您不明白为什么,请考虑创建一个有效的 std::string 对象需要分配内存来保存字符串数据——这就是 std::string 构造函数做。从文件中读取数据不可能做到这一点。

文件是字节流。要将数据写入文件,您需要定义某种方式将该数据表示为字节流。如果它是可变长度,则需要对其长度进行编码。要读回它,您还需要处理可变长度的情况。您需要将文件数据转换为适当的内部表示,例如 std::string。这称为“序列化”。

关于c++ - 从文件 C++ 访问对象时出现读取访问冲突。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49421723/

相关文章:

c++ - 在类中存储对对象的 const 引用

c++ - 带有构造函数的类的匿名 union/结构

c++ - 如何从 C 文件调用 Cpp 函数

c++ - 在Python(或C++)中将一个实体减去另一个实体

c++ - Wt泄漏内存吗?

c++ - 如何在比较中使用成员函数?

c++ - 二元运算符的最佳命名空间是什么?

c++ - 为什么不使用 is_const 类型特征将 const 引用视为 const?

c++ - 为什么需要转发返回值

具有隔离键/值的 C++ 缓存友好 HashMap