0

very new to c++ . have an assignment when am to input some information about an item and write to a file . Have succesfully done that but now i i dont know how to delete a line of entry from the text file and save it . look at so many ways the one method i saw deletes the whole contents of the file which is not what i need ,

the delete function had to just delete the word typed and delete all the entries on that line . not the entire contents of the file

void deletefind() {
string deleteline;
string line;
ifstream in("Coreship.txt");
if (!in.is_open()) {
    cout << "Input file failed to open\n";
        }
ofstream out("outfile.txt");

cout << "Please Select the Vessel you would like to remove" << endl;
cin >> deleteline;
while (getline(in, deleteline)) {
    if (line != deleteline)
        out << line << endl;
}
in.close();
out.close();
remove("Coreship.txt");
rename("outfile.txt", "Coreship.txt");

cout << "\nChanges has Successfully been made...... Data Saved\n" << endl;
3
Contributors
2
Replies
13
Views
4 Months
Discussion Span
Last Post by Nihar_2
0

On line 12, the code should be:
while (getline(in, line)) {

The way you have it now, the string line is never assigned a value.

You might also want to intialize line, just to guard against the possibility that the random contents of line equals deleteline at startup.

0

Here is a pseudocode,

  1. read the entire file into a vector
  2. delete that file
  3. create and write back the data to the file skipping the line that isn't required.
    Use std::getline() in a loop to read a line from the file.

Learn C++ here https://hackr.io/tutorials/learn-c-c-plus-plus

Load the file content into memory,
delete the line there,
and write the content back to file.
You could somewhat optimize this process by not loading the portion of the file before the line being deleted (though you'd still need to scan it to find the "target" line), but you won't be able to do much better than that without a specialized data structure.

If this is really important performance-wise, consider using a database instead of the plain file.

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.