我正在尝试读取我创建的一个 .bin 文件,该文件在一个结构中包含两个整数和一个字符串。 int 显示正常,但字符串输出以某种方式显示奇怪的符号。
这是写脚本:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct student{
int no;
string name;
int score;
};
int main(){
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<char*>(&jay),sizeof(student));
myFile.write(reinterpret_cast<char*>(&brad),sizeof(student));
myFile.close();
cin.get();
return 0;
}
这是读取脚本:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct student{
int no;
string name;
int score;
};
int main(){
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<char*>(&readFile),sizeof(student));
cout << "No : " << readFile.no << endl;
cout << "Name : " << readFile.name << endl;
cout << "Score: " << readFile.score << endl;
myFile.close();
cin.get();
return 0;
}
结果是这样的:
No : 200
Name : ñ∩K
Score: 83
字符串显示“ñ∩K”而不是“Brad”。
我尝试不使用 seekp
,而是使用 read 两次:
myFile.read(reinterpret_cast<char*>(&readFile),sizeof(student));
cout << "No : " << readFile.no << endl;
cout << "Name : " << readFile.name << endl;
cout << "Score: " << readFile.score << endl;
myFile.read(reinterpret_cast<char*>(&readFile),sizeof(student));
cout << "No : " << readFile.no << endl;
cout << "Name : " << readFile.name << endl;
cout << "Score: " << readFile.score << endl;
结果是:
No : 100
Name : Jay
Score: 95
No : 200
Name : ε@
Score: 83
如您所见,第一个位置显示“Jay”正常,但下一个位置不正确。知道出了什么问题吗?我是 C++ 新手。
最佳答案
您写入文件的不是字符串,而是 std::string
对象的内部结构。可能这是一个指针。当您读回它时,指针将指向无效的内容。你很幸运能得到任何输出,而不是崩溃,或者恶魔从你的鼻孔里飞出来。
关于c++ - 无法使用 fstream 从二进制文件中读取字符串,而是显示奇怪的符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55390123/