Frage

I enter text into textBox, and when button is clicked how can I delete line(entered in textBox) from file?

My deleting method code:

public: System::Void deleteOneRejuser() 
    {
        string fileName = "mainBase/main.txt";
        fstream file;

        file.open(fileName, ios::in);

        char buf[255];
        string text;

        //read all lines in file and write in 'buf'
        while(file.getline(buf,255,'\n'));

        //converting
        text = (const char*) buf;

        //convert textBox text in string    
        System::String^ myString = textBox2->Text;
        string str = msclr::interop::marshal_as< string >( myString);

        int pos = text.find(str);

        if ( pos == (int) string::npos )
            this->label2->Text = "Bad line, not found";

        text.erase( pos, str.size() );

        file.close();

        file.open(fileName, ios::out);
        file << text;
        file.close();
    }

VS 2010 Windows Forms

War es hilfreich?

Lösung

Your reading loop will read all lines, but will discard all but the last line:

//read all lines in file and write in 'buf'
while(file.getline(buf,255,'\n'));

This is because the getline call just overwrites the contents in buf, it does not append.

Instead do something like

//read all lines in file and append to 'text'
while(file.getline(buf,255,'\n'))
    text += buf;
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top