我创建了一个从文本文件中读取,向内容添加内容,显示联系人的函数。然后它会提示用户选择要删除的联系人。该程序删除了联系人,但它也删除了其他联系人(不是全部)。 这是代码:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cstdio>
#include <iomanip>
using namespace std;
vector<string> contakt;
void deleteContact()
{
ifstream input;
input.open("contacts.txt");
string entry;
int contactID=0;
int index = contactID;
while (getline(input, entry))
{
contakt.push_back(entry);
}
input.close();
cout << "\n\n\nCurrent contacts in list: "<< endl;
if (contakt.size() == 0) cout << "Empty" <<endl;
for (int i = 0; i < contakt.size(); i++)
{
cout << i << ") " << contakt[i] << endl;
}
cout<< " Enter the Id of the contact you would like to remove"<<endl;
cin>> contactID;
if (index != -1)
{
ofstream output;
output.open("temp.txt");
for (vector<string>::iterator it = contakt.begin(); it!= contakt.end(); it++)
{
contakt.erase(contakt.begin() + index);
output<< *it <<'\n';
}
remove("contacts.txt");
rename("temp.txt", "contacts.txt");
output.close();
cout << "Contact deleted succesfull." << endl;
}
else cout << "\nNote: Id was not found in file." <<endl;
return;
}
代码
我从开始重新制作功能,现在我面临另一个问题。 在删除联系人时,文件末尾会创建一个空格。
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
void deleteContact()
{
vector<string> file;
string temp;
ifstream input("contacts.txt");
while( !input.eof() )
{
getline(input, temp);
file.push_back(temp);
}
input.close();
string item;
cout << "Enter an name to delete from the contacts: ";
cin>>item;
int t = 0;
for(int i = 0; i < (int)file.size(); ++i)
{
if(file[i].substr(0, item.length()) == item)
{
file.erase(file.begin() + i);
cout << "Order erased!"<< endl;
i = 0; // Reset search
t++;
}
}
if (t == 0) cout<< "There is no contact with that name!!"<< endl;
ofstream output("contacts.txt", ios::out | ios::trunc);
for(vector<string>::const_iterator i = file.begin(); i != file.end(); ++i)
{
output << *i << '\n';
}
output.close();
return;
}
答案 0 :(得分:2)
您的代码会在向量迭代时修改向量。 这使迭代器无效。 检索从erase()函数返回的更新迭代器。
此处有更多详情:iterate vector, remove certain items as I go
或者,因为您似乎一次只删除一个联系人,只需在第一次调用擦除后中断您的for循环。