cuốn sách gpt4 ai đã làm

c++ - 无法使用 fstream 从二进制文件中读取字符串,而是显示奇怪的符号

In lại Tác giả: Walker 123 更新时间:2023-11-28 01:22:42 26 4
mua khóa gpt4 Nike

我正在尝试读取我创建的一个 .bin 文件,该文件在一个结构中包含两个整数和一个字符串。 int 显示正常,但字符串输出以某种方式显示奇怪的符号。

这是写脚本:

#include 
#include
#include

sử dụng không gian tên std;

struct student{
int no;
tên chuỗi;
int score;
};

int chính(){
fstream myFile;
myFile.open("data.bin", ios::trunc | ios::out | ios::in | ios::binary);

student jay, brad;

jay.no = 100;
jay.name = "Jay";
jay.score = 95;

brad.no = 200;
brad.name = "Brad";
brad.score = 83;

myFile.write(reinterpret_cast(&jay),sizeof(student));
myFile.write(reinterpret_cast(&brad),sizeof(student));

myFile.close();

cin.get();
trả về 0;
}

这是读取脚本:

#include 
#include
#include

sử dụng không gian tên std;

struct student{
int no;
tên chuỗi;
int score;
};

int chính(){
fstream myFile;
myFile.open("data.bin", ios::in | ios::binary);

student readFile;

myFile.seekp(1*sizeOf(student)); //I use this because I want only specific position
//to be shown, for example I put 1 to show only Brad

myFile.read(reinterpret_cast(&readFile),sizeof(student));
cout << "No : " << readFile.no << endl;
cout << "Name : " << readFile.name << endl;
cout << "Score: " << readFile.score << endl;

myFile.close();

cin.get();
trả về 0;
}

Kết quả là thế này:

No : 200
Name : ñ∩K
Score: 83

字符串显示“ñ∩K”而不是“Brad”。我尝试不使用 seekp,而是使用 read 两次:

    myFile.read(reinterpret_cast(&readFile),sizeof(student));
cout << "No : " << readFile.no << endl;
cout << "Name : " << readFile.name << endl;
cout << "Score: " << readFile.score << endl;

myFile.read(reinterpret_cast(&readFile),sizeof(student));
cout << "No : " << readFile.no << endl;
cout << "Name : " << readFile.name << endl;
cout << "Score: " << readFile.score << endl;

hóa ra:

No : 100
Name : Jay
Score: 95

No : 200
Name : ε@
Score: 83

如您所见,第一个位置显示“Jay”正常,但下一个位置不正确。知道出了什么问题吗?我是 C++ 新手。

câu trả lời hay nhất

您写入文件的不是字符串,而是 std::chuỗi 对象的内部结构。可能这是一个指针。当您读回它时,指针将指向无效的内容。你很幸运能得到任何输出,而不是崩溃,或者恶魔从你的鼻孔里飞出来。

关于c++ - 无法使用 fstream 从二进制文件中读取字符串,而是显示奇怪的符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55390123/

26 4 0
Walker 123
Hồ sơ

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá taxi Didi miễn phí
Phiếu giảm giá taxi Didi
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress