从文件C ++中删除行(textBox)

时间:2014-05-03 12:39:56

标签: c++-cli

我在textBox中输入文字,当点击按钮时如何从文件中删除行(在textBox中输入)?

我的删除方法代码:

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窗体

1 个答案:

答案 0 :(得分:0)

您的阅读循环将读取所有行,但将丢弃除最后一行之外的所有行:

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

这是因为getline调用只会覆盖buf中的内容,但不附加。

而是做类似

的事情
//read all lines in file and append to 'text'
while(file.getline(buf,255,'\n'))
    text += buf;