C++在将字符串写入二进制文件时写入访问违规
这是一些代表我较大程序应该做的事情的一部分的代码。它运行绝对很好。
但是,当我将书籍内部的变量类型从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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论