我正在使用此文件:
cookie1
1
2
3
cookie2
4
5
6
cookie3
7
8
9
cookie4
10
11
12
cookie5
13
14
15
我需要从用户那里获取num并选择使用它来选择他们选择的cookie号码并允许他们在数量上添加一个数字,这是cookie类型之后的第一个数字。
这是我的代码:
void AddQuantity (fstream &file)
{
char user_choice[SIZE];
int i = 1;
Cookies tempCookies;
int num;
file.open("cookie.dat", ios::in | ios::out | ios::app);
file.clear();
file.seekg(0L, ios::beg);
file >> tempCookies.description;
file >> tempCookies.quantity_sold;
file >> tempCookies.cost;
file >> tempCookies.price;
while (!file.eof())
{
cout << i << ". " << tempCookies.description << endl;
file >> tempCookies.description;
file >> tempCookies.quantity_sold;
file >> tempCookies.cost;
file >> tempCookies.price;
i++;
};
cout << endl;
file.clear();
cout << "Enter the number of the cookie type that you would like to modify: ";
cin >> num;
cout << endl;
file.seekg((num - 1)* sizeof(Cookies), ios::beg);
return;
}
答案 0 :(得分:0)
声明后file.seekg((num - 1)* sizeof(Cookies), ios::beg);
您现在可以将cookie修改为
file.read( (char *)&tempCookies, sizeof(Cookies) );//used to read the required cookie
file.seekg((num - 1)* sizeof(Cookies), ios::beg);//shifting back file pointer by one cookie object
tempCookies.quantity_sold = new_value;//updating the value
file.write( (char *)&tempCookies, sizeof(Cookies) );//writing the value to the file.