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

时间:2019-03-28 04:21:30

标签: 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,而是使用两次读取:

    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 ++的新手。

1 个答案:

答案 0 :(得分:2)

您要写入文件的不是字符串,而是std::string对象的内部结构。可能那是一个指针。当您读回它时,指针将指向无效的内容。您很幸运能获得所有输出,而不是崩溃或恶魔从鼻孔飞出。