【问题标题】:string array writing reading from binary file c++字符串数组写入从二进制文件c ++中读取
【发布时间】:2017-11-06 14:15:12
【问题描述】:

我正在开发我的项目,它是一个烹饪助手,它指导用户执行存储在二进制文件中的任务。我无法将输入保存到文件中并再次读回。我在下面包含了我的代码。建议我执行此操作的方法或在我的代码中进行更正。我想获取存储在二维数组中的指令......我必须得到输入,直到特定配方的指令和成分结束。我正在研究 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();
}

【问题讨论】:

  • 您可能想阅读以下内容:stackoverflow.com/questions/5605125/… 您还应该考虑将您的 qty/unit/ingredient/instruction 拆分为自己的结构,并使用配方类中的向量来跟踪事物.你需要序列化每个变量而不是编写一个块,但如果你想让它变得健壮,你确实需要这样做。
  • 如果iostream.h 可用,您似乎也在使用非常旧的编译器。有几种现代的免费编译器可供选择,您也可以考虑一下。
  • 我建议拼出首字母缩写词,因为大多数应用程序都有足够的内存用于“您要继续吗?”。
  • 您应该尝试使用正确的序列化,而不是将指向您的类的指针转换为 char*。我不确定它是否是未定义的行为,但它肯定是不可移植的。

标签: c++ arrays string file


【解决方案1】:

在一系列写入之后,您在文件的末尾有了一个文件位置。当你开始阅读时,你仍然在文件的末尾,那里没有什么可以读的。

要回到开头,您可以搜索file.seekg(0, ios::beg);

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-08
    • 2021-07-02
    • 2016-01-15
    • 2014-06-18
    • 1970-01-01
    相关资源
    最近更新 更多