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

标签 c++

我正在尝试读取我创建的一个 .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/

相关文章:

c++ - 如何在 C++ 中从 dll(dll 中的构造函数)创建一些类?

c++ - 当要读取的文件已经打开时,文件读取进入无限循环

c++ - ofstream 泄漏内存

c++ - 使用递归函数查找字符串回文

c++ - STL list_iterator代码题(STL 4.0.0)

c# - 关于 CoCreateInstance() 方法实现的问题

c++ - 了解此 `const&` 特化的必要性

c++ - 表达式中运算符的 GCC 和 ADL

c++ - 需要有关此 C++ 代码的帮助

c++ - 在一个字节中交换半字节