从二进制文件 C++ 读取的字符串数组写入
string array writing reading from binary file c++
>我正在处理我的项目,这是一个烹饪助手,它指示用户执行存储在二进制文件中的任务。我无法将输入保存到文件中并再次读回。我在下面包含了我的代码。建议我一种方法来执行此操作或更正我的代码。我想获取存储在二维数组中的指令...我必须获得输入,直到特定食谱的说明和成分结束。我正在研究 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
。
相关文章:
- 使用 jsoncpp 解析 json 数组字符串
- C++ 对象数组字符串输入在控制台上不起作用
- 插入了 C++ 数组字符串数据,但在显示输出时不显示
- 无法区分 JSON 对象/数组/字符串
- 为什么数组(字符串类型)的大小是 24 字节,带有单个空格元素
- 如何使用数组字符串进行输入验证
- (C++) 打印字符数组字符串的单词时出现问题
- 使用Back_inserter从任何位置的输入字符中使用Back_inserter进行过滤数组字符串
- C 函数反转字符数组字符串
- 如何在 c++ 中创建数组(字符串 [] )的向量
- 如何返回数组字符串的指针
- char数组字符串混淆
- 如何从字符数组字符串中提取空格
- 是否可以将 Bitset<8> 的值复制到数组字符串而不转换它们?
- C++数组字符串函数
- 如何在函数中操作字符数组(字符串)的指针,该指针在C / C ++中作为参数传递
- visual将音频文件存储到数组/字符串流C++中
- c++在char数组(字符串)上将what替换为
- 将数组字符串转换为intger c++(初学者)
- 需要设置数组字符串长度,使其恰好为13