从二进制文件 C++ 读取的字符串数组写入

string array writing reading from binary file c++

本文关键字:数组 字符串 二进制文件 C++ 读取      更新时间:2023-10-16

>我正在处理我的项目,这是一个烹饪助手,它指示用户执行存储在二进制文件中的任务。我无法将输入保存到文件中并再次读回。我在下面包含了我的代码。建议我一种方法来执行此操作或更正我的代码。我想获取存储在二维数组中的指令...我必须获得输入,直到特定食谱的说明和成分结束。我正在研究 c++

#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<process.h>
class recipe {
    int laststate, icount, qcount;
    char recno;
    char name[50];
    float quantity[][50];
    char ingredient[][50];
    char instructions[][50];
    char unit[5];
public:
    recipe() {
        //if(laststate>recno)
        //recno=laststate;
        //else
        recno = 0;
    }

    void add() {
        char ch;
        cout << "nEnter Recipe Name :";
        cin >> name;
        do {
            qcount = 0;
            cout << "nQuantity, Unit and Ingredient Name :";
            cin >> quantity[qcount] >> unit[qcount] >> ingredient[qcount];
            qcount++;
            cout << "nDo You Want to Enter More Ingredients :";
            cin >> ch;
        } while (ch == 'y' || ch == 'Y');
        do {
            icount = 0;
            cout << "nEnter Instructions:n";
            cin >> instructions[icount];
            icount++;
            cout << "nDo You Want to Enter More Instructions :";
            cin >> ch;
        } while (ch == 'y' || ch == 'Y');
        recno++;
        laststate = recno;
    }
    void display() {
        cout << "Recipe Name :" << name << endl;
        cout << "Ingredients :" << endl;
        for (int i = 0; i <= qcount; i++)
            cout << i + 1 << "." << quantity[i] << " " << unit[i] << " ";//<<ingredient[i]<<endl;
        for (i = 0; i <= icount; i++)
            cout << i + 1 << "." << instructions[i] << endl;
        cout << "last state :" << laststate;
    }
};
void main() {
    clrscr();
    recipe R;
    char ch;
    fstream file("DATA.DAT", ios::binary | ios::app);
    do {
        R.add();
        file.write((char*)&R, sizeof(R));
        cout << "DYWTC :";
        cin >> ch;
    } while (ch == 'y' || ch == 'Y');
    while (!file.eof()) {
        file.read((char*)&R, sizeof(R));
        R.display();
    }
    file.close();
    getch();
}

经过一系列写入后,文件的位置位于文件的最后。当您开始阅读时,您仍然在文件的末尾,那里没有什么可阅读的。

要回到起点,您可以做一个 搜索file.seekg(0, ios::beg); .

此外,要同时启用读取和写入,您可能还需要在调用 open 中添加ios::in | ios::out