在txt文件中的getline(cin,(variable))之后无法删除nextline

时间:2013-12-30 06:47:41

标签: c++ function ifstream getline ofstream

我正在编写一个简单的程序,用户可以:

答:添加新客户端
B:见客户名单
C:删除数据库
D:删除客户端

它在大多数情况下运作良好,问题基本上是每个客户也有债务。 债务显示在客户名称下面的行中。

Name: bryan
Debt: 45.56$

Name: Rosa
Debt: 23.43$

Name: Jon
Debt: 55.55$

我想这样做,以便当客户端的名称被删除时,它下面的行也是如此,等等。什么代码可以使这个工作?我只用了大约1个月的时间进入c ++所以如果可以的话请为我愚蠢地理解我会非常感激。 :)

我的代码:

#include <iostream>
#include <fstream>
#include <string>

using namespace std ;

int kill();
int end() ;
int read() ;
int append() ;
int main() 
{
  string input ;
  double cash ;
  cout << "A simple program to enter information about clients.\n" ;
  cout << "________________" << endl ;
  cout << "If you wish to add a new client, press A. \n" ;
  cout << "If you wish to see the list of existing clients, press B. \n" ;
  cout << "If you wish to delete this file, press C. \n" ;
  cout << "If you wish to delete a client, press D. \n" ;
  cout << "________________" << endl ;

  getline(cin, input ) ;
  cout << endl ;
  cout << endl ;
  cout << endl ;
  if(input == "A")
  {
    append() ;
  }
  if(input == "B")
  {
    read() ;
  }
  if(input == "C")
  {
    string input2;
    cout << "Are you sure you wish to delete the entire file? You will lose the 
      information.\n"
    cout <<"Enter C again, if you are sure: " ;
    getline(cin, input2);
    if(input2 == "C")
    {
     end();
    }

  }
  if(input == "D")
  {
    kill();
  }
  return 0 ;
}

int kill()
{
  string deleteline, nextline ;
  string line;
  ifstream kill; 
  kill.open("Clients.txt") ;
  ofstream temp ;
  temp.open("temp.txt") ;
  cout << "What Client do you wish to delete from the database?\n" ;
  getline(cin, deleteline) ;
  deleteline = "Name: " + deleteline;
  while (getline(kill,line))
  {
     if (line != deleteline )
     {
      temp << line << endl ;            
     }
  }
  temp.close();
  kill.close();
  remove("Clients.txt");
  rename("temp.txt","Clients.txt");
}


int append()
{
  string name ; 
  double cash ;

  ofstream writer("Clients.txt" , ios::app) ;
  cout << "Enter the client's name: " ;
  getline(cin, name) ;
  cout << "\n" ;
  cout << "Enter the client's debt balance: " ;
  cin >> cash ;
  cout << endl ;
  writer <<"Name: " << name << endl ;
  writer <<"Debt: ";  
  writer << cash << "$" << endl ;
  writer << "\n" ;
  writer.close() ;
}

int read()
{
  string line ;
  ifstream read("Clients.txt") ;
  if(read.is_open())
  {
    while(getline(read , line))
    {
        cout << line << "\n" ;
    }
    read.close() ;
  }
}

int end()
{
  ofstream ofs ;
  ofs.open("Clients.txt", ios::out | ios::trunc);   
  ofs.close() ;
}

主要问题在于我的kill()函数,它负责删除行,并在用户输入“D”时被调用。

1 个答案:

答案 0 :(得分:2)

不用写它就读它:

while (getline(kill,line))
{
   if (line != deleteline )
   {
      temp << line << endl ;            
   }
   else
   {
      getline(kill, line);   // Error handling is pretty irrelevant here.
   }
}