【发布时间】:2020-01-05 07:07:38
【问题描述】:
我有一个任务是从用户那里获取输入并将其写入文件并成功写入文件,如下面给出的函数,它运行良好
void add_category(string NAME, int ID_category)
{
category* newnode;
newnode = new category;
newnode->name_of_category = NAME;
newnode->id = ID_category;
if (headd == NULL) {
headd = newnode;
newnode->next = NULL;
newnode->pre = NULL;
lastd = newnode;
}
else {
lastd->next = newnode;
newnode->pre = lastd;
newnode->next = NULL;
lastd = newnode;
}
dlength++;
ofstream file("Category.txt", ios::app);
category* temp = headd;
category* temp2;
while (temp != NULL) {
file << temp->name_of_category << endl;
file << temp->id << endl;
temp2 = temp;
temp = temp->next;
delete temp2;
}
file.close();
}
但问题是,当通过代码打开文件时会崩溃或 TBH,我不知道如何打开文件。我正在使用双链表。我的任务是以读取模式打开文件并删除用户输入的类别。这是我删除类别的功能:
void delete_category(string remove_name)
{
category* currentptr = headd;
category* temp;
category* temp2;
category* temp3 = headd;
ifstream file("Category.txt");
if (!file) {
cout << "file can not open" << endl;
}
else {
while (temp3 != NULL && !file.eof()) {
file >> temp3->name_of_category;
file >> temp3->id;
temp3 = temp3->next;
}
}
int save = search_category(remove_name);
cout << save << endl;
if (dlength <= 0) {
cout << " NO category found" << endl;
}
else {
if (save == 0) {
temp = headd;
headd = headd->next;
headd->pre = NULL;
}
else {
for (int i = 1; i < save; i++) {
currentptr = currentptr->next;
}
temp = currentptr->next;
temp2 = temp->next;
currentptr->next = temp2;
temp2->pre = currentptr;
}
dlength--;
delete temp;
cout << " Successfully Deleted the Category" << endl;
}
}
由于我在删除类别中调用了搜索功能,因此我在搜索功能中使用相同的方法打开文件:
int search_category(string search)
{
category* currentptr = headd;
int flag = 0;
category* temp3 = headd;
ifstream file("Category.txt");
if (!file) {
cout << "file can not open" << endl;
}
else {
while (temp3 != NULL && !file.eof()) {
file >> temp3->name_of_category;
file >> temp3->id;
temp3 = temp3->next;
}
}
for (int i = 0; i < dlength; i++) {
if (currentptr->name_of_category == search) {
flag = 1;
return i;
}
currentptr = currentptr->next;
}
if (flag == 0) {
cout << " Sorry not found" << endl;
return -1;
}
}
请纠正我在打开文件时出错的地方。
【问题讨论】:
标签: c++ data-structures file-handling