mình có đoạn ct ghi file nhị phân như sau
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void ghi(string, string);
int main(){
string str = "test";
ghi("output.dat", str);
system("pause");
return 0;
}
void ghi(string name,string str){
ofstream ghi(name, ios::binary);
ghi.write(reinterpret_cast <char *> (&str), sizeof(str));
cout << "Write data finished" << endl;
ghi.close();
}
và đọc như sau
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void doc(string);
int main(){
string name = "output.dat";
doc(name);
system("pause");
return 0;
}
void doc(string name){
ifstream doc(name, ios::binary);
if (!doc){
cout << "File not found" << endl;
return;
}
string str;
doc.read(reinterpret_cast <char *> (&str), sizeof(str));
doc.close();
cout << str << endl;
}
nhưng khi chạy ct đọc,nó đọc đúng, nhưng có 1 lỗi hiện thị như sau
lỗi là do đâu nhỉ,
mình thấy nghi vấn chỗ doc.read(reinterpret_cast <char *> (&str), sizeof(str));
bản chất string là 1 vector, giờ chuyển nó về con trỏ kiểu char có vấn đề gì k ta?
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?