0

I tried to remove a single line from a file using user input and ended up removing all the lines.

  /*inside of the file looks like this //courseName_c.str() file
   1. Intro to C Programming
   2. Data Type // this is the one i want to remove
   3. Function
  */

void Topic::removeTopic() {
    Course CO;
    string courseName = "";
    string topicName = "";
    string content = "";

    cout<<"Remove Topic" << endl;
    ifstream topiclist(courseName.c_str()); /*courseName contains the list of the topic from which i intend to delete a specific line using user input but ending up deleting all the line in it */

    while(getline(topiclist, content)) {
        std::cout  << content << endl ; 
    }

    cout << "Type the Topic Name you want to Remove: " ;

    getline(cin, topicName);
    ofstream temp;
    temp.open("temp");
    while(getline(topiclist, content)) {
        content.replace(content.find(content),content.length(),"");
        temp << content << endl;
    }
/*while (getline(topiclist, content))
{

  if (content != topicName)   //i also tried like this
  {
  temp << content << endl;
  }
}
*/  
    topicist.close();
    temp.close();
    remove(courseName.c_str());
    rename("temp", courseName.c_str());
// this part is for removing the associating file and it works perfectly
    if (remove(topicName.c_str( )) !=0)
        cout<<"\n\nRemove operation failed"<<endl;
    else
        cout<< topicName<<" has been removed."<<endl;
}    `
qdot
  • 6,195
  • 5
  • 44
  • 95
MEHEDI HASAN
  • 149
  • 4
  • 11
  • Typo? `content.find(content)`, not `content.find(topicName)`? – user4581301 Nov 27 '16 at 07:45
  • 1
    A handy tool that comes with any development environment worth using [is the debugger](https://en.wikipedia.org/wiki/Debugger). With it you can control the execution of your program, stepping through it line by line if need be, and inspect the variables as you go. It can make finding mistakes in simple programs almost effortless. As a programmer learning to use debuggers is pretty much a mandatory skill. – user4581301 Nov 27 '16 at 07:53
  • 1
    You should have searched SO and google. Check this if it helps: http://stackoverflow.com/questions/9505085/replace-a-line-in-text-file – Mohammad Yusuf Nov 27 '16 at 07:55
  • ya sorry that was a typo. content.find(topicName),topicName.length() is the right one i suppose. but still removing all the text from the file – MEHEDI HASAN Nov 27 '16 at 07:56

0 Answers0