Thecube Thecube - 3 months ago 25
C++ Question

Deleting specific lines in a text file based one 1 variable

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

artist:title:year:category

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
do{
cout << "Please enter the name of the file you would like to delete from: ";
cin >> oldfile;
oldfile += ".txt";
openFile.open(oldfile.c_str());
if(openFile.fail()){
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])){
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

xxxx:Ruby:xxxx:xxxx

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

Answer

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 (openFile.fail()) return;

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

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

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);
        break;
    }
}

openFile.close();

openFile.open(filename, 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.

Comments