gpt4 book ai didi

c++ - 删除/修改结构数组中的元素

转载 作者:行者123 更新时间:2023-11-30 00:58:21 24 4
gpt4 key购买 nike

我有一个程序可以将“ friend ”信息存储到结构数组中并将其写入文件。没问题。但是我怎样才能修改和/或删除该结构数组中的特定元素呢?做了一些阅读,它说我不能,除非我在删除后将它全部移动一个。

所以我假设我需要读入它,然后删除它,然后将所有其他元素移动一个并再次写入...但是我该怎么做呢?尝试仅包括我目前拥有的必要代码。

为了修改它,我想我会读入它,然后询问我要更改的特定元素,然后将该元素中的所有值设置为 null,然后允许用户输入新信息?这段代码看起来如何?

struct FriendList
{
char screenname[32];
char country[32];
char city[32];
char interests[32];
short age;

};

int main()
{
FriendList friends[num_friends];
const int num_friends = 2;

// Gets user input and puts it into struct array and writes to file

case 3:
{ // Getting info and putting in struct elements
for (index = 0; index < num_friends; index++)
{
// Create Friend Records
cout << "Enter Screename " << endl;
cin.ignore();
cin.getline(friends[index].screenname, 32);
cout << "Country: " << endl;
cin >> friends[index].country;
cout << "City: " << endl;
cin >> friends[index].city;
cout << "Age: " << endl;
cin >> friends[index].age;

}
counting += index;

fstream infile;
infile.open("friends.dat", ios::out | ios::binary |ios::app);
if(infile.fail())
{ cout << "File not found!\n\t";
// exit
}

// Writing struct to file
infile.write((char*)&friends, sizeof(friends));

infile.close();

break;
}

// Delete a friend ???
case 5:
{ // Reading in file contents into struct friends
// Then????
fstream outfile;
outfile.open("friends.dat", ios::in | ios::binary);
outfile.read((char*)&friends, sizeof(friends));

break;
}

最佳答案

是的,它可以修改结构的成员。但是你一开始不清除内存,你会在friends.dat中看到车库。在main的上层,最好加上memset()

memset(&friends, 0, sizeof(friends));

并且您使用 ios::app 。我猜 friends 是全套数据。那么,您应该删除 ios::app 吗?

顺便说一句,在 C++ 后期,大多数 c++er 不使用二进制文件来处理这种情况。 :)

关于c++ - 删除/修改结构数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6435318/

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