I am trying to finish my program and I need it to delete a line from a text file. I've tried multiple code from other people in trying to figure out why my "temp.txt" file won't rename and replace my "fruit.txt" file which is the file I was deleting a line from.
main.cpp
#include <iostream>
#include "filehandling.h"
using namespace std;
int main()
{
program run;
run.askUser();
return 0;
}
filehandling.h
#ifndef FILEHANDLING_H_INCLUDED
#define FILEHANDLING_H_INCLUDED
#include <fstream>
#include <iostream>
#include <string>
#include <cstdio>
#include <vector>
using namespace std;
class program{
public:
string name;
string desc;
ofstream out_stream;
ifstream in_stream;
void displayMenu () // Display for Menu
{
cout << "--------------------Welcome To Lemon Mart---------------------" << endl;
cout << "\t1: Add a Fruit to your cart." << endl;
cout << "\t2: Delete a item from your cart." << endl;
cout << "\t3: List of items in your shopping cart." << endl;
cout << "\t4: Checkout(Ends Program)." << endl;
}
void createFile() // Creates the file
{
out_stream.open ("fruit.txt");
if(!out_stream.is_open())
{
cout << "Output file failed." << endl;
exit(1);
}
}
void writeToFile(string fruitName) // Writes Input to the file
{
out_stream << fruitName << endl;
}
void listFruits() // fills array from file
{
in_stream.open("fruit.txt");
vector<string> fruitVec;
string str;
while (getline(in_stream, str))
{
if(str.size() > 0)
fruitVec.push_back(str);
}
cout << "Here's a list of what items you have in your cart currently" << endl << endl;
for (string & line : fruitVec)
cout << line << endl;
cout << endl << endl;
in_stream.close();
}
void delItem(string path,string eraseFruit)
{
string line;
ifstream fin;
fin.open(path);
ofstream temp;
temp.open("temp.txt");
while (getline(fin, line))
{
if (line != eraseFruit)
temp << line << endl;
}
temp.close();
fin.close();
const char * p = path.c_str();
remove(p);
rename("temp.txt", p);
}
void askUser()
{
int choice = 0;
string path = "fruit.txt";
string eraseFruit;
createFile();
while(choice <= 3)
{
displayMenu();
cin >> choice;
cout << endl;
switch (choice)
{
case 1 :
// ADD FRUIT TO BASCKET
cout << "Whats the name of the fruit you wish to add to your cart?" << endl;
cin >> name;
cout << "Item added to cart." << endl << endl;
writeToFile(name);
choice = 0;
break;
case 2 :
// Delete item from cart
cout << "What item would you like to delete from your cart?" << endl;
cin >> eraseFruit;
delItem(path, eraseFruit);
choice = 0;
break;
case 3 :
// List Cart items
listFruits();
choice = 0;
break;
case 4 :
// Exits Program
cout << "\tChecking Out, Have a good day!" << endl;
exit(1);
break;
default :
cout << "Must select a option" << endl;
choice = 0;
break;
}
}
out_stream.close();
}
};
#endif // FILEHANDLING_H_INCLUDED