Removing line from file

66 Views Asked by At

I've got an error from compiler:

Unhandled exception at 0x7486A832 in Nowy.exe: Microsoft C++ 
exception: std::out_of_range at memory location 0x00B3F2F4.

After debbuging it seems an error ocurres here:

if (plik.good() == true)
{
    int number_of_lines = 0;
    string line;
    while (std::getline(plik, line))
    {
        if (number_of_lines == deleteLineNumber)
        {
            line.replace(0,line.length(), ""); // <--------- HERE IS ERROR
            //cout << "Line has been deleted!";
            break;
        }

        ++number_of_lines;
    }
}

Where am I making mistake? This code was supposed to remove one line from a file

1

There are 1 best solutions below

5
On

std::out_of_range is an exception you get when you attempt to access memory outside the space you've allocated (in an STL container). In this particular case, you are accessing areas of a std::string that has not been allocated:

Try replacing line[0] by line.begin() and line.length() by line.end():

line.replace(line.begin(),line.end(), "");

If you want to remove the line completely then try:

line.erase(line.begin(), line.end());