从文本文件中删除记录

时间:2014-04-25 14:48:42

标签: c++ file-io row-removal

我有一个使用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;
    }
  }
}

1 个答案:

答案 0 :(得分:2)

您可以在检查名称的语句中添加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; } } } 之后引入一个计数器,以便跳过以下几行:

{{1}}