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

问题描述 投票:0回答:1

我正在尝试读取我创建的.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,并且使用了两次读取:

    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

正如你所看到的,第一个位置显示“杰伊”很好,但下一个位置不是。知道出了什么问题吗?我是C ++的新手。

c++
1个回答
2
投票

你写的文件不是字符串,而是std::string对象的内部结构。可能那是指针。当你重读它时,指针将指向无效的东西。你很幸运能得到任何输出而不是崩溃,或者从你的鼻孔飞来的恶魔。

© www.soinside.com 2019 - 2024. All rights reserved.