gpt4 book ai didi

c++ - 从文件写入和读取数据时丢失数据(随机访问文件,C++)

转载 作者:太空宇宙 更新时间:2023-11-04 11:40:15 26 4
gpt4 key购买 nike

首先,我通过写入以下数据来初始化“hardware.dat”文件,然后以列表形式显示它们。 enter image description here enter image description here

但是,当我处理选项 2 然后退出选项 2 而不编辑或添加任何内容时,所有数据都丢失了。我提议什么都不会改变。 enter image description here

为什么会出现这个问题?如何解决?

感谢您的关注。


代码:

int question_3()
{
cout << "Question 3" << endl;
create_One_Hundred_blank_Data();
char choice = '0';
do
{
cout << "---------------Main Menu---------------" << endl
<< "1. Initialize hardware data." << endl
<< "2. Add / Edit data." << endl
<< "3. Remove data." << endl
<< "4. Show whole data in the file." << endl;
cout << "Enter choice > "; choice = getch(); cout << choice << endl; // #include <conio.h>
switch_Choice(choice);
}while (choice != '0');

cout << "Program is ended." << endl;
return 0;
}


void switch_Choice(char choice)
{
switch (choice)
{
case '1':
choice_1();
break;

case '2':
choice_2();
break;

case '3':
choice_3();
break;

case '4':
choice_4();
break;
}
}



void choice_2()
{
hardware.open("hardware.dat", ios::binary | ios::out);
if (!hardware)
{
cerr << "File could not be opened." << endl;
exit(1);
}

int record = 0;
string tool_name = "";
int quantity = 0;
int cost = 0;
string buffer_Eater = "";

cout << "Enter record number <O to exit input> : "; cin >> record;
while(record != 0)
{
cout << "Enter tool name : "; getline(cin, tool_name); getline(cin, buffer_Eater);
cout << "Enter quantity : "; cin >> quantity;
cout << "Enter cost : "; cin >> cost;

write_Single_Data(myHardwareData, record, tool_name, quantity, cost);

cout << "Enter record number <O to exit input> : "; cin >> record;
}
hardware.close();
output_Whole_File_Data();
separation_line();
}



void output_Whole_File_Data()
{
hardware.open("hardware.dat", ios::binary | ios::in);
output_Data_LineHead();
hardware.read(reinterpret_cast<char *>(&myHardwareData), sizeof(HardwareData));
int counter = 0;
cout << setprecision(2) << fixed;
while (hardware && !hardware.eof())
{
if (myHardwareData.getRecord() != 0)
output_Data_Line(cout, myHardwareData);

hardware.read(reinterpret_cast<char *>(&myHardwareData), sizeof(HardwareData));
}
hardware.close();
}

最佳答案

尝试替换

hardware.open("hardware.dat", ios::binary | ios::out);

通过

hardware.open("hardware.dat", ios::binary | ios::out | ios::app);

关于c++ - 从文件写入和读取数据时丢失数据(随机访问文件,C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21676502/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com