1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
|
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
void openFile(ofstream &in, string fileName);
void openFile(ifstream &in, string fileName);
void deleteAnimal(ifstream &in, string animal, string inFileName);
void outputFile(ifstream &out);
int main()
{
string fileName("Animals.txt");
ifstream inFile;
string animal;
openFile(inFile, fileName);
outputFile(inFile);
inFile.close();
openFile(inFile, fileName);
cout << "What animal would you like to delete: ";
getline(cin, animal);
cout << endl;
deleteAnimal(inFile, animal, fileName);
outputFile(inFile);
cin.ignore();
return 0;
}
void openFile(ifstream &stream, string fileName)
{
stream.open(fileName);
if (!stream)
{
cout << fileName << " could not be opened";
cin.ignore();
exit(1);
}
}
void openFile(ofstream &stream, string fileName)
{
stream.open(fileName);
if (!stream)
{
cout << fileName << " could not be opened";
cin.ignore();
exit(1);
}
}
void deleteAnimal(ifstream &in, string animal, string inFileName)
{
ofstream outStream;
string fileName = "temp.txt";
string temp;
openFile(outStream, fileName);
while (getline(in, temp))
{
if (temp.find(animal) == std::string::npos)
outStream << temp << endl;
}
outStream.close();
in.close();
openFile(outStream, inFileName);
openFile(in, fileName);
while (getline(in, temp))
{
outStream << temp << endl;
}
in.close();
outStream.close();
openFile(in, inFileName);
}
void outputFile(ifstream &out)
{
string temp;
while (getline(out, temp))
{
cout << temp << endl;
}
}
|