Hi, i want to read some lines to an output text file in a loop. My problem is, that i want to start clearing the text file and then append to it in a loop. At the moment i use:

ofstream file;
file.clear();
file.open("book.txt", ios::app);
for (map<string,Person>::const_iterator it = adrbook.begin();
        it != adrbook.end(); ++it) {
        file.open("book.txt");
        string name = it -> second.get_Name();
                file << name;
        }
file.close();

my problem is, that it does not clear the content of the file, so i am just appending on a file with content from previous runs.

file.open("book.txt", ios::app);

Do you see that ios:app? It is telling the compiler to append whatever to book.txt
So, if you want to start afresh, just remover that ios::app tag
Use

file.open("book.txt",ios::trunc);

or you can even simply use

file.open("book.txt");

Thanks for the reply. But when i remove the ios:app, it just adds my first input, and igoneres whatever comes after. For example if i have 5 names and the first one is "Carl", i just see "Carl" in the text file?

Thanks!

Look at your code:

for (map<string,Person>::const_iterator it = adrbook.begin();
it != adrbook.end(); ++it) {
file.open("book.txt");

Do you realize that you have put the file.open() in a for loop.
And file.close() outside the loop ?
So the remedy is to put the file.open() outside the loop. And it would work just fine.

PS: I see you changing your code in your original post by using edit functionality. Don't do this. If anyone else will view this thread, it will avoid confusion to him. So, please don't change anything of your post after a reply has been given to it. In that case just re-submit it again

i have put my open outside the loop now, and it still does not work. I am really confused now. Thanks for the advice though.

Dude, first of all you didn't followed my advice, I said you not to modify your orignal post.
But anyways, if you look at your code again you will find that, there still is a file.open inside the loop. Moreover, the file.open() you have put outside the loop contains the ios::app
so now getting frustrated I am posting your code in corrected form:

ofstream file;
file.clear();//I dont know why you need this, u shd remove it
file.open("book.txt");
for (map<string,Person>::const_iterator it = adrbook.begin();
it != adrbook.end(); ++it) 
{
[INDENT]string name = it -> second.get_Name();
file << name;[/INDENT]
}
file.close();

You don't need clear() and you should check if you've actually opened the file. Why are you using const_iterator, does it need to be const?

ofstream file(filename.c_str());
if(file.is_open())
{
    //do stuff...
    file.close();
}
else
    cout << "Failed to open: " << filename << endl;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.