gpt4 book ai didi

c++ - 从文本文件中删除记录

转载 作者:行者123 更新时间:2023-11-30 04:05:26 25 4
gpt4 key购买 nike

我有一个作业项目要使用 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;
}
}
}

最佳答案

您可以在检查名称的语句中添加一个 else 子句,并引入一个计数器,计算在找到 name 后应跳过的以下行数:

int skip = 0;
while (getline(myfile, line)) {
if ((line != name) && !(skip > 0)) {
temp << line << endl;
}
else {
if(skip == 0) {
skip = 2; // Skip the next two lines also
}
else {
--skip;
}
}
}

关于c++ - 从文本文件中删除记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23296364/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com