I got a task that is: Write a simple program that can be used to delete data on one one line specified in a file with the following steps: Manually create a file containing:
i. Fill from line 1
ii. Fill from line 2
ii. Fill from line 3
iv. Fill in line 4
Display the entire contents of the file. Appears the choice of how many rows to delete. Delete data in the selected row. Display the entire contents of the file.
I have created the program as below:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
// Function Prototipe
void garis();
void show_databefore();
void show_data();
void del_line(const char *file_name, int n);
// Variable Declaration
int n;
ifstream myFile;
string output,buffer;
// Main Function
int main(){
cout << "Show data and delete specific line Program " << endl;
garis ();
cout << "The Data " << endl;
show_databefore();
garis();
cout << "Select the Rows of data you want to delete: ";
cin >> n;
cout << "\nBefore " << endl;
// If Case after input n
if((0 < n) && (n < 100)){
del_line("data1.txt", n); // this process will delete the row that has been selected.
} else {
cout << "Error" << endl;}
show_data(); // when calling this function. Display on the console, data is displayed 2 times.
return 0;
}
//Function to delete data in the row that has been selected
void del_line(const char *file_name, int n){
ifstream fin(file_name);
ofstream fout;
fout.open("temp.txt", ios::out);
char ch;
int line = 1;
while(fin.get(ch))
{
if(ch == '\n')
line++;
if(line != n)
fout<<ch;
}
fout.close();
fin.close();
remove(file_name);
rename("temp.txt", file_name);
}
// Function to display data1.txt to the console
void show_databefore(){
myFile.open("data1.txt");
while (!myFile.eof()){
getline(myFile,buffer);
output.append("\n" + buffer);
}
cout << output << endl;
myFile.close();
}
// Function to display data1.txt to the console T
// This fuction actually same as show_databefore.
void show_data(){
myFile.open("data1.txt");
while (!myFile.eof()){
getline(myFile,buffer);
output.append("\n" + buffer);
}
cout << output;
myFile.close();
}
//Function to provide a boundary line.
void garis(){
cout << "======================================================= " << endl << endl;
}
When I run my program it works, but when I bring up data to the console, my data appears 2 times and I've tried the method without using the function. However, the result remains the same.
Can anyone help me? Or maybe there's an easier way to build my program? Thank you