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

时间:2011-06-22 05:29:01

标签: c++ arrays struct

我有一个程序将“朋友”信息存储到struct数组中并将其写入文件。没问题。但是,我如何能够修改和/或删除该结构数组中的特定元素?做了一些阅读并且它说我不能,除非我在删除之后将其全部改为一个。

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

为了修改它,我猜我会读它,然后询问我想要更改的特定元素#,然后将该元素中的所有值设置为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;
        }

4 个答案:

答案 0 :(得分:3)

是的,它可以修改结构的成员。但是你不会在第一次清除记忆,你会在friends.dat看到车库。 在main的上方,你最好添加memset()

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

你使用ios :: app。我想friends是完整数据集。那么,你应该删除ios :: app?

BTW,在C ++的最新版本中,大多数c ++ er并不像这种情况那样使用二进制文件。 :)

答案 1 :(得分:1)

更改相对容易 - 只需阅读正确的条目,在内存中更新并回写。为了删除我建议如下:

  1. 阅读您需要删除的条目后的所有条目

  2. 将这些条目写入已删除条目的偏移量

  3. 将fuile截断到新的长度

  4. 这是一个简单的方法

答案 2 :(得分:1)

听起来你想要std :: deque或std :: vector取决于用法。

如果您不经常删除项目,请使用std :: vector而不是固定数组:

std::vector<FriendList> friends;

添加新朋友:

friends.push_back(newFriend);

通过索引访问朋友与访问数组相同:

friends[index]

要删除向量中的条目,请使用erase()(而不是remove()!):

friends.erase(friends.begin() + index)

答案 3 :(得分:1)

你可以删除一个方法,在你要删除的朋友之后拉出朋友,将信息移动到当前结构,然后继续,直到没有更多的朋友。

相关问题