Я пишу простую программу, в которой пользователь может:
A: добавить нового клиента
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 name: " ;
getline(cin, name) ;
cout << "\n" ;
cout << "Enter the client 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".
Прочтите его, не написав:
while (getline(kill,line))
{
if (line != deleteline )
{
temp << line << endl ;
}
else
{
getline(kill, line); // Error handling is pretty irrelevant here.
}
}