Thecube Thecube - 2 years ago 110
C++ Question

Deleting specific lines in a text file based one 1 variable

Currently got 4 different variables, saved in the format of:


I am currently opening the file and saving into corresponding variables, I have tried using getline, but unable to get it to delete all the corresponding variables.

void deletesong(){

string oldfile;
ifstream openFile;
ofstream ofile;
string line;
string songnme;
string oartist[NUM], otitle[NUM], oyear[NUM], ocategory[NUM];
int counter;
bool finddvd;
//User enters filename, add .txt to make sure its saved as filename.txt
cout << "Please enter the name of the file you would like to delete from: ";
cin >> oldfile;
oldfile += ".txt";;
cerr << "Check spelling of file name.\n";
error = true;
//Storing text from file into arrays
}while(error == true);

while(getline( openFile, oartist[counter], ':') && getline( openFile, otitle[counter], ':') &&
getline( openFile, oyear[counter], ':') && getline( openFile, ocategory[counter])){
cout << "Enter the name of the song you would like to delete: ";
cin >> songname;

This is the code I am using to retrive the filename, and then open the file and save everything into the arrays.

What I need my code to do is to for example is if someone wants to delete a song name of Ruby, it will be in the textfile as


I need the program to delete all the information on the line as its one record.

Answer Source

You want to use std::vector<std::string> rather than declaring array of strings, such as string oartist[NUM]

See also stackoverflow std::vector documentation

In addition, you can organize your data in to one structure. For example:

struct record
    std::string artist, title, year, category;

Use std::vector::push_back to add data. You can then remove records which are in the middle of the vector, or you can add new data to the vector. Finally save the data. For example:

std::fstream openFile(filename, std::ios::in);
if ( return;

record rec;
std::vector<record> songs;

while ( getline(openFile, rec.artist, ':') && 
    getline(openFile, rec.title, ':') && 
    getline(openFile, rec.year, ':') && 
    getline(openFile, rec.category) )

std::string title_remove = "title";

for (size_t i = 0; i < songs.size(); i++)
    if (songs[i].title == title_remove)
        songs.erase(songs.begin() + i);

openFile.close();, std::ios::out);
for (size_t i = 0; i < songs.size(); i++)
    openFile << songs[i].artist << ":" 
    << songs[i].title << ":" 
    << songs[i].year << ":" 
    << songs[i].category << "\n";

Note that this example uses fstream instead of using ofstream. That's because it needs to open the file for reading, then close the file, and open it again with ios::out flag for writing.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download