C++在将字符串写入二进制文件时写入访问违规

发布于 2025-01-22 07:54:25 字数 768 浏览 1 评论 0原文

这是一些代表我较大程序应该做的事情的一部分的代码。它运行绝对很好。

但是,当我将书籍内部的变量类型从int转换为字符串和编写字符串而不是在那里写字符串时,Visual Studio将我带到了Xmemory页面,其中说“写访问违规”。

#include <fstream>
#include <string>
#include <iostream>
    
using namespace std;
    
struct book
{
    int name, author;
};

int main()
{
    setlocale(LC_ALL, ".866");
    book var;
    var.author = 1;
    var.name = 2;
    
    ofstream outFile;
    outFile.open("file.bin", ios::binary);
    outFile.write((char*)&var, sizeof(book));
    outFile.close();

    book newVar;

    ifstream inFile;
    inFile.open("file.bin", ios::binary);
    inFile.read((char*)&newVar, sizeof(book));
    inFile.close();

    cout << newVar.name;
}

为什么这个以及如何解决字符串?我想我错过了一些非常基本和非常重要的东西

Here's some code that represnts a part of what my bigger program should do. It runs absolutely fine.

However, when I change the types of variables inside of book from int to string and write strings instead of numbers there, Visual Studio takes me to the xmemory page where it says "Write access violation".

#include <fstream>
#include <string>
#include <iostream>
    
using namespace std;
    
struct book
{
    int name, author;
};

int main()
{
    setlocale(LC_ALL, ".866");
    book var;
    var.author = 1;
    var.name = 2;
    
    ofstream outFile;
    outFile.open("file.bin", ios::binary);
    outFile.write((char*)&var, sizeof(book));
    outFile.close();

    book newVar;

    ifstream inFile;
    inFile.open("file.bin", ios::binary);
    inFile.read((char*)&newVar, sizeof(book));
    inFile.close();

    cout << newVar.name;
}

Why is this and how to fix that for string? I think I have missed something very basic and very important

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文