我是c ++的初学者,我正在尝试使用添加,搜索和删除联系人的一些简单功能创建联系人列表。 我是初学者(所以很好),我尽量使这段代码变得简单。
问题是我的删除功能无法正常工作。 我已经有一个添加功能,它将选择的联系人存储到.txt文件中,在我的删除功能中,我使用ifstream从我的.txt文件中读取联系人,我创建了一个新的Ofstream = temp,然后我尝试读取所有联系人(没有我要删除的)到我的临时,最后我尝试删除我以前的原始.txt文件并将我的temp重命名为我的主.txt文件。问题是,即使我删除了我原来的.txt文件,它仍然存在于目录映射中,我不知道为什么。 我的删除功能似乎也没有正常工作,因为它似乎只能删除一个联系人,当我尝试删除另一个联系人时,新的联系人被删除但是第一个被删除的联系人再次出现。我的代码出了什么问题?
到目前为止,我有3个不同的.cpp文件。 main.cpp,add.cpp和delete.cpp以及1个标题。
我的添加功能只会将联系人添加到带有ofstream的.txt文件中,文本文件在添加联系人后会如下所示:
(姓名:Bob Dylan
电子邮件:bob_dylan.bob@bob.se
地址:Bobdylansroad
出生日期:blabla
Phonenumber:2343298492384)
因此,每个联系人总共存储5行,如果有人能告诉我为什么它不能删除并正常工作,那么初学者的建议会有所帮助!
这是我的删除功能:
#include <iostream>
#include "Header.h"
#include <string>
#include <fstream>
#include <stdio.h>
using namespace std;
void del()
{
checkpoint:
int menu = 3;
string line, name;
cout << "------------------------------------------------------"
<< '\n'
<< " Please Enter the name of Contact you want to delete: "
<< '\n'
<< "------------------------------------------------------"
<< endl;
cin.ignore();
getline(cin, name);
ifstream textbook;
ofstream temp;
textbook.open("Textbook.txt");
temp.open("temp.txt", ios::app);
while (menu)
{
if (menu == 2)
{
textbook.close();
cout << "Going back to main menu" << endl;
system("pause");
system("cls");
return;
}
else if (menu == 1)
{
goto checkpoint;
}
else if (menu == 3)
{
//this is where all contacts except for the chosen one + the next
// 4 lines are read to the temp object
int skip = 0;
while (getline(textbook, line))
{
if (line != name && !(skip > 0))
{
temp << line << endl;
}
else
{
if(skip == 0)
{
skip = 4;
}
else
{
--skip;
}
}
}
cout << "The contact with the name " << name << " has
been deleted if it exsisted" << endl;
system("pause");
temp.close();
textbook.close();
remove("Textbook.txt");
rename("temp.txt", "Textbook.txt");
cout << '\n'
<< "Press 1 for: deleting another contact" << '\n'
<< "Press 2 for: Going back to Main menu" << '\n'
<< endl;
cin >> menu;
}
}
}