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

Recommended Answers

All 2 Replies

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.

Okay. Great!

You guys are of a great help for us beginners.

Third problem solved since joining your forum :)

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.