【发布时间】: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*。我不确定它是否是未定义的行为,但它肯定是不可移植的。