简体   繁体   中英

How do I delete a new line from the end of a text file?

I'm deleting a line from a text file by copying each line, except for the one line specified by the user which is to be deleted, to a new text file (temp.txt) and then deleting the original text file (staffMembers.txt) and renaming temp.txt to staffMembers.txt.

The content of staffMembers.txt is as follows:

1 | First Person | Manager | 123.45
2 | Second Person | Full Time | 123.45
3 | Third Person | Casual | 123.45

When the content of staffMembers.txt is copied to temp.txt it is as follows:

1 | First Person | Manager | 123.45
2 | Second Person | Full Time | 123.45
3 | Third Person | Casual | 123.45
*** new line ***

Could someone please explain how I can prevent that new line from being created at the end of the text file? My code is as follows:

void deleteStaffMember()
{
    outStream.open("temp.txt", ios::app);

    if(outStream.fail())
    {
        cout << "Unable to open temp.txt.\n";
        exit(1);
    }

    inStream.open("staffMembers.txt");

    if(inStream.fail())
    {
        cout << "Unable to open staffMembers.txt.\n";
        exit(1);
    }
    else
    {
        cout << endl << "Please enter a staff members ID to delete: ";
        cin >> deleteLine;

        while(getline(inStream, line))
        {
            string firstCharacter;

            firstCharacter += line[0];

            if (firstCharacter != deleteLine)
            {
                outStream << line << endl;
            }
            else
            {
                inStream.close();

                outStream.close();

                cout << "Error. Unable to find staff member.\n" << endl;

                break;
            }
        }
    }

    inStream.close();

    outStream.close();

    remove("staffMembers.txt");

    rename("temp.txt", "staffMembers.txt");

    cout << "The staff member has been deleted successfully.\n" << endl;

    system("pause");

    system("cls");
}

I cannot remove endl from outStream << line << endl; because then temp.txt is formatted like the following:

1 | First Person | Manager | 123.452 | Second Person | Full Time | 123.453 | Third Person | Casual | 123.45

cleaner solution by using a vector

string line;
vector<string> lines;

// put all lines into a vector  
while ( getline(inStream, line) ) {
  lines.push_back( line );
}

// remove the line begin with character deleLine....   
std::remove_if( lines.begin(), lines.end(), 
                [](string &line) { return line[0] == deleteLine; } );

// append newline to every line except last line  
std::for_each( lines.begin(), line.end() - 1,
                []( string &line ) { line += '\n'; } );

// write lines to new file
std::for_each( lines.begin(), line.end(),
                []( string &line ) { outStream << line; } );

Just change the logic a bit, like so:

    bool firstLine = true;

    while(getline(inStream, line))
    {
        string firstCharacter;

        firstCharacter += line[0];

        if (firstCharacter != deleteLine)
        {
            if (!firstLine)
            {
                outStream << endl;
            }
            outStream << line;
            firstLine = false;
        }
        else
        {
            inStream.close();

            outStream.close();

            cout << "Error. Unable to find staff member.\n" << endl;

            break;
        }
    }

This way we print new lines BEFORE each line, except for on the first line.

The code:

if (firstCharacter != deleteLine)
{
    outStream << line << endl;
}

Is likely the culprit.

It is outputting the line, and then adding the '\\n', which is one of the things that 'endl' does.

Consider the case where 'line' is the empty string, or nearly so.

The behaviour will become rather obvious if you use this code instead:

if (firstCharacter != deleteLine)
{
    outStream << "{" << line << "}" << endl;
}

And finally, decide how you want to cater for that last line. yngum's answer is very good, I suggest understanding his code.

(Hint: The '\\n' does not actually mean "End of line", it can be interpreted as any of "Line separator", "Start of new line", or "End of line")

just add this is if statement

if(line != ""){
    Myfile << line << endl ; 
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM