首页 > 解决方案 > 如何在 C++ 中将带有空格的字符数组写入二进制文件?以及如何阅读它们?

问题描述

现在我正在大学做我的课程项目。我需要帮助。我想创建一个简单的字典。我正在使用二进制文件方法来做到这一点。在下面的代码中,我试图编写也包含空格的文本行。但我得到错误的输出。有没有人可以帮助我将带有空格的文本写入二进制文件并阅读它们?

//These are global variables in my code
string sword;
string sdefinition;


这是我的课:

class Input
{
public:
    char word[50];
    char definition[300];
    void input()
    {
        cout << "Enter a new word: ";
        getline(cin, sword);
        sword.copy(word, sword.size() + 1);
            cout << "Enter the definition: ";
        getline(cin, sdefinition);
        sdefinition.copy(definition, sdefinition.size() + 1);
    }
    void output()
    {
        for (int i = 0; i < strlen(word); i++)
        {cout << word[i];}
        cout << endl;

        for (int i = 0; i < strlen(definition); i++)
        {cout << definition[i];}
        cout << endl;
    }
};

这是我的主要功能:

int main()
{
    ofstream a("data", ios::app | ios::binary);
    Input i;
    i.input();
    a.write((char*)&i, sizeof(i));
    a.close();
    ifstream b("data", ios::binary);
    b.read((char*)&i, sizeof(i));
    i.output();
    b.close();
    return 0;
}

标签: c++classfstreambinaryfiles

解决方案


推荐阅读