如何从电话簿程序中删除联系人

How to delete a contact from a phonebook program

本文关键字:删除 联系人 程序 电话簿      更新时间:2023-10-16

我制作了一个电话簿程序,其中包括添加和搜索联系人。

但是当我使用删除功能时,它删除了所有联系人而不是我输入的联系人。

我知道这有点复杂,但有什么想法吗?

这是电话簿中的输入.txt我想从中删除联系人:

Barney Hackett      0114543053
Luis Avery      01056633489
Hudson Ramsay       01576633982

Ihe代码是:

void DeletePhoneNumber() {
FILE* search, * fp1;
//to receive the enter from system("cls")
char temp;
scanf("%c", &temp);
search = fopen("PHONEBOOK.txt", "r+");
fp1 = fopen("temp.txt", "w");
system("cls");
printf("t*****DELETE CONTACT*****");
printf("nt Enter Name: ");
int length;
length = strlen(SearchName);
int i, y = 0;
//string comparison//
while (fgets(name, 50, search) != NULL) {
fputs(name, fp1);
}
fclose(search);
fclose(fp1);
search = fopen("PHONEBOOK.txt", "w");
fp1 = fopen("temp.txt", "r");
while (fgets(name, 50, search) != NULL) {

fputs(name, search);
}
fclose(search);
fclose(fp1);
remove("temp.txt");
printf("ntPRESS ANY KEY TO CONTINUE");
getch();
MainMenu();
}
}

我将使用这个"答案"空间来对代码进行部分分析。您可以使用它来改进代码。

基本上,你的循环都是错误的:

search = fopen("PHONEBOOK.txt", "r+");
while (fgets(name, 50, search) != NULL) {
// ...
while (token != NULL) {
// ...
fclose(search);
search = fopen("PHONEBOOK.txt", "w");

您在追加模式下打开了文件,从中读取,现在关闭文件,以其他模式打开它。它会在 while 循环的下一个fgets读取什么?

在模式"w"中打开文件进行写入将销毁文件。所以这就是为什么你的文件中没有更多的条目。

fclose(search);
MainMenu();

在循环的底部,关闭文件。它怎么还能在 while 循环中读取带有fgets的东西。

接下来你打电话给MainMenu。但是我假设这个函数调用这个DeletePhoneNumber函数,所以你处于一个奇怪的循环/递归中。当然,当您完成删除电话号码后,您只需返回主菜单,而不是再次拨打它。