954,498 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Writing to file problem

Hello.

I have a problem writing to a file using for loop.

here is the code:

/* the code should save numbers in a file something like this

1 5
2 8
3 7
4 6
*/

//instead it gives just the last numbers it catches
/*

4 6

*/
for(int i=0;i<=4;i++){
    //some code before

    int iCom = (rand()%3+5);

    ofstream played("played.txt");
    if (played.is_open()){
        played << i << " " << iCom;
        played << endl;
        played.close();	                                              
    }
    else cout << "Unable to save" << endl;
}


Thanks

niggz
Light Poster
26 posts since Jun 2011
Reputation Points: 10
Solved Threads: 0
 

You open the file for writing on each iteration. This truncates it to zero length before writing. Try opening the file before the loop and leaving it open until after the loop completes.

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

Okay. Great!

You guys are of a great help for us beginners.

Third problem solved since joining your forum :)

niggz
Light Poster
26 posts since Jun 2011
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: