【发布时间】:2018-03-19 21:33:52
【问题描述】:
给定一个包含多个元素的 struct 数组,我想删除元素 2,并希望元素 3、4、5.. 转移到 2、3、4。
在我下面的代码中,添加和删除功能可以正常工作。我尝试过使用 strcpy() 函数,但它没有用。
struct Books {
char title[20];
char author[20];
};
void add_book(struct Books book1[], int *counter){
fflush(stdin);
printf("Title: ");
gets(book1[*counter].title);
printf("Author: ");
gets(book1[*counter].author);
*counter++;
return;
}
void delete_book(struct Books book1[], int *counter){
int i = 0;
int delete = 0;
printf("What nr of book you want to delete: ");
scanf("%d", &delete);
book1[delete-1].title[0] = '\0';
book1[delete-1].author[0] = '\0';
*counter--;
/*
here I want to move elements down one step if I delete for example one
element in the middle
*/
return;
}
int main(){
struct Books book1[50];
int count = 0; //for keeping track of how many books in the register
add_book(book1, &count);
delete_book(book1, &count);
return 0;
}
【问题讨论】:
-
memmove是一个非常好的函数,可以在内存中移动(重叠)数据。 -
另请注意,下降
fflush并传递一个仅输入流(如stdin)在C 规范中明确提到为undefined behavior。一些标准库实现已将其添加为扩展,但请尽量避免。 -
这个问题已经在这里回答了stackoverflow.com/questions/15821123/…
-
我只使用了 fflush,因为没有它 add_book 函数就无法工作
-
@Benji 那是因为你用错了
scanf。