Jeremy Sharp
Jeremy Sharp

Reputation: 27

Outputting multiple lines to a text file

I've done this before, but can't find the sample code...still new to c++.

I need to output multiple lines to a text file. Right now it only outputs the last line, so I assume its overwriting the prior line each time the loop is run. How do I get it to output a line and then output to the next line, etc. without writing over the prior line?

Here's a snippet:

    int main()
{
    int n = 1;

    while (n <= 100)
    {
        int argument = 0 + n;

        ofstream textfile;
        textfile.open ("textfile.txt");
        textfile << argument << endl;
        textfile.close();

        ++n;
    }

    return 0;
}

Upvotes: 0

Views: 16351

Answers (4)

Vishnu
Vishnu

Reputation: 2110

Use this instead :

int main()
{
    int n = 1;

    while (n <= 100)
    {
        int argument = 0 + n;

        ofstream textfile;
        textfile.open ("textfile.txt", ofstream::out | ofstream::app);
        textfile << argument << endl;
        textfile.close();

        ++n;
    }

    return 0;
}

Upvotes: -1

nmjohn
nmjohn

Reputation: 1432

It looks like the default open mode is override, so it's only going to write over anything in the file previously with what is being currently written into the file.

Below are to keep the file handle open instead of reopening many times. If you want to append still you should use this :

textfile.open ("textfile.txt", ios::out | ios::app);

This will open the file for output and append on the end of the file.

int main()
{
int n = 1;

ofstream textfile;
textfile.open ("textfile.txt");

while (n <= 100)
    {
    int argument = 0 + n;

    textfile << argument << endl;

    ++n;
    }
textfile.close();

return 0;
}

Upvotes: 2

dlowe
dlowe

Reputation: 159

You should open and close the file outside of the loop. When the file is opened, it defaults to overwriting. You can specify an append mode, but since opening a file is a somewhat lengthy operation, you don't really want to do that in this case.

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272762

Open the file before you enter the loop, and close it after you exit the loop.

Upvotes: 5

Related Questions