【发布时间】:2012-06-08 01:24:16
【问题描述】:
我在将字符串写入二进制文件时遇到问题。这是我的代码:
ofstream outfile("myfile.txt", ofstream::binary);
std::string text = "Text";
outfile.write((char*) &text, sizeof (string));
outfile.close();
然后,我尝试阅读它,
char* buffer = (char*) malloc(sizeof(string));
ifstream infile("myfile.txt", ifstream::binary);
infile.read(buffer, sizeof (prueba));
std::string* elem = (string*) buffer;
cout << *elem;
infile.close();
我只是无法让它工作。对不起,我只是绝望。谢谢!
【问题讨论】:
-
看起来您正在编写字符串对象数据,但这可能不会写入存储在对象中的 TEXT。您应该在 C++ 中使用 Streams。相当于 outfile
-
@Mark 快速搜索显示:cplusplus.com/reference/string/string
-
请发布一些真实的、复制粘贴的代码。假设
string是std::string,这不会编译:string *text = "Text"; -
这里有很多错误,基本理解 C++ 是如何工作的。你看起来像是一个试图让 C++ 工作的 C 程序员。你应该停下来阅读一本关于 C++ 的书。最重要的是,要意识到 C++ 是一种不同的动物(你几乎不应该使用
malloc)。 -
@BillJames - “快速搜索”在这里没有帮助,因为
string可以是任何东西,不一定是std::string。