我正在处理我的项目,这是一个烹饪助手,指示用户执行存储在二进制文件中的任务。我无法将输入保存到文件中并再次读回。我在下面提供了我的代码。建议我在我的代码中执行此操作或更正的方法。我想得到存储在二维数组中的指令......我必须得到输入,直到特定配方的说明和成分结束。我正在研究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();
}
答案 0 :(得分:0)
在一系列写入之后,您在文件的最后有一个文件位置。当你开始阅读时,你仍然在文件的末尾,没有什么可读的。
要回到起点,您可以进行搜寻/**
* Create an unset function using Lodash
* @param state
* @param payload
*/
unsetById: ( state, payload ) => {
// Remove the item
Vue.delete( state.data, _.findIndex( state.data,{ id: payload.id } ) );
// Emit an event to the event bus
EventBus.$emit( 'screen-deleted' );
}
。
此外,要同时启用阅读和写作,您可能还需要在file.seekg(0, ios::beg);
的调用中添加ios::in | ios::out
。