This asks the user for the file name and the number of lines they want to remove. It then stores each line into a vector. An dynamic array is used the hold the random line numbers(generated by random generator) and the corresponding element in the vector is deleted. This vector is then copied to a new file named "temp.txt" where each element is it's own line.
Questions:
What can I improve to make this code for efficient? ie. Better methods to perform this task?
What should I not use and should change? (for example any bad habits?)
What did I use that is good and should keep it as a habit.
Are there any exceptions I can use to ensure code.
Warnings I recieved:
1.Warning C26495 Variable 'LineEditor::array' is uninitialized. Always initialize a member variable (type.6). for LineEditor().
2.Avoid unnamed objects with custom construction and destruction (es.84). for getFileName() in void removeLines().
#include <iostream>
#include <string>
#include <fstream>
#include <random>
#include <ctime>
#include <cstring>
#include <vector>
#include <algorithm>
#include <iterator>
template<typename T>
void writeTo(const std::string& filename, std::vector<T>& v)
{
std::ofstream fstream(filename);
if (!fstream)
exit(1);
std::copy(v.begin(), v.end(), std::ostream_iterator<T>(fstream, "\n"));
fstream.close();
}
class LineEditor
{
std::vector<std::string> buf;
std::string fileName;
int noOfLines{ 0 };
int* array;
public:
LineEditor()
{
}
~LineEditor()
{
std::cout << "\"" << fileName << "\"" << " " << noOfLines << " lines removed.\n";
delete[] array;
}
void removeLines()
{
getFileName();
TotalLinesToRemove();
std::ifstream fileIn;
std::string line;
int lineCounter{ 0 };
int* array = new int[noOfLines];
fileIn.open(fileName);
if (!fileIn)
{
std::cerr << fileName << " can not be opened." << std::endl;
exit(1);
}
while (fileIn.is_open())
{
while (std::getline(fileIn, line))
{
lineCounter++;
buf.push_back(line);
}
for (int i{ 0 }; i < noOfLines; ++i)
{
array[i] = getRandomNumber(0, lineCounter - 1);
buf.erase(buf.begin() + (array[i]));
--lineCounter;
}
writeTo("temp.txt", buf);
fileIn.close();
}
}
private:
std::string getFileName()
{
std::cout << "Enter name of text file: ";
std::cin >> fileName;
return fileName;
}
int TotalLinesToRemove()
{
std::cout << "Enter the number of lines to remove: ";
std::cin >> noOfLines;
return noOfLines;
}
int getRandomNumber(int min, int max)
{
std::mt19937 seed{ static_cast<std::mt19937::result_type>(std::time(nullptr)) };
std::uniform_int_distribution<> rand(min, max);
return rand(seed);
}
};
int main()
{
LineEditor file;
file.removeLines();
return 0;
}
Thank you for taking your time to help me. I am fairly beginner to intermediate at c++ and want to improve.