【发布时间】:2014-04-25 14:48:41
【问题描述】:
我有一个作业项目,要使用 C++ 编写一个程序,该程序在一个文本文件中维护一个学生列表(他们的姓名、年龄和 GPA)。该程序具有以下功能:
- 插入记录
- 删除记录
- 搜索记录
- 更新记录
删除记录时,我的代码将字符串名称作为输入并将其从文本文件中删除。但是,文件中的下两行(该学生的年龄和 gpa)被保留。我该如何删除它们?
以下是我的程序的代码。
#include <iostream>
#include <fstream>
using namespace std;
void writing();
void deleting();
void searching();
class student {
public:
int age = 0;
string name;
void SetGpa(float x)
{
gpa = x;
}
float GetGpa()
{
return gpa;
}
private:
float gpa = 0.0;
};
int main()
{
int opt;
cout << "Please Enter an option number to continue:\n ";
cout << "\nPress 1 for New Record insertion";
cout << "\nPress 2 for Record Deletion";
cout << "\nPress 3 for Searching a Record";
cout << "\nPress 4 for Updating a Record";
cout << "\nEnter option Number: ";
cin >> opt;
switch (opt)
{
case 1:
{
writing();
break;
}
case 2:
{
deleting();
break;
}
case 3:
{
searching();
break;
}
case 4:
{
deleting();
writing();
cout << "Record has been updated! ";
break;
}
}
}
void writing()
{
float a;
student moiz;
cout << "Please enter name of student: ";
cin >> moiz.name;
cout << "Please enter the age of student: ";
cin >> moiz.age;
cout << "Pleae enter the Gpa of student: ";
cin >> a;
moiz.SetGpa(a);
ofstream myfile;
myfile.open("record.txt", ios::app | ios::out);
myfile << endl << moiz.name << endl;
myfile << moiz.age << endl;
myfile << moiz.GetGpa();
myfile.close();
}
void deleting()
{
string line, name;
cout << "Please Enter the name of record you want to delete: ";
cin >> name;
ifstream myfile;
ofstream temp;
myfile.open("record.txt");
temp.open("temp.txt");
while (getline(myfile, line))
{
if (line != name)
temp << line << endl;
}
cout << "The record with the name " << name << " has been deleted if it exsisted" << endl;
myfile.close();
temp.close();
remove("record.txt");
rename("temp.txt", "record.txt");
}
void searching()
{
ifstream fileInput;
fileInput.open("record.txt");
string line, search;
cout << "Please enter the term to search: ";
cin >> search;
for (unsigned int curLine = 0; getline(fileInput, line); curLine++)
{
if (line.find(search) != string::npos)
{
cout << "found: " << search << " on line: " << curLine << endl;
}
else
{
cout << "Error! Not found on Line" << curLine << endl;
}
}
}
【问题讨论】:
-
您没有提出任何问题,也没有提出任何问题。你需要更具体。而且你应该非常具体,不要对家庭作业问题投反对票。人们确实在这里帮助了这些人,但必须表现出在询问部分的重大努力。
-
我在问题的一开始就展示了提问的部分。目前这个程序只从文本文件中删除我想要的名称是它应该从文本文件中删除 Name+Age+Gpa。
-
好的,我试过了......也许我的英语太糟糕了,但是:“Deleting a record from text file in C++”, “I have got an分配项目以使用 c++ 制作一个程序,该程序将执行以下操作。","我完成了该项目,唯一的问题是我想删除整个记录[...]”,我没问题。你说你想要什么,而不是你的问题是什么。我只是想向您介绍一些社区标准,因为您似乎是新人。尝试做某事,然后用例子说出什么是行不通的,然后尝试问为什么。我什么都可以,我只是不喜欢新用户收到
-5s。 -
好吧,我的问题是,在删除 () 函数中,当名称字符串被删除时,我还想删除接下来的 2 行 AGE 和 GPA。现在你能帮帮我吗?
-
@StringName 查看我的回答,它应该可以解决您的问题。最好只发布有问题的代码,并更清楚地了解问题中的问题。
标签: c++ file-io row-removal