如何从电话簿程序中删除联系人
How to delete a contact from a phonebook program
我制作了一个电话簿程序,其中包括添加和搜索联系人。
但是当我使用删除功能时,它删除了所有联系人而不是我输入的联系人。
我知道这有点复杂,但有什么想法吗?
这是电话簿中的输入.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
函数,所以你处于一个奇怪的循环/递归中。当然,当您完成删除电话号码后,您只需返回主菜单,而不是再次拨打它。
相关文章:
- 将数组的地址分配给变量并删除
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- C/C++编译器通常会删除重复的库吗
- 从链接列表c++中删除一个项目
- C++如何通过用户输入删除列表元素
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 是否需要删除包含对象的"pair"?
- 如何在自删除后将对象设置为nullptr
- 迭代时从向量和内存中删除对象
- 使用函数"remove"删除重复元素
- 如何从多映射中删除特定的重复项
- 运算符C++ "delete []"仅删除 2 个前值
- 删除指向指针的指针是运行时错误吗
- 将指针设置为"nullptr"并不能防止双重删除?
- 为什么示例代码访问IUnknown中已删除的内存
- 如何通过 getter 函数删除矢量的元素?
- 从控制台中删除最后打印的元素
- C++中的线程安全删除
- 如何从电话簿程序中删除联系人
- 添加/删除/更新联系人时获得通知