-1

Is it possible to write all output to a text file

Expected output (in the text file):

car

bike

plane

Actual output:

plane

Code (I tried a for loop) :

string vehicle[3]= { "car", "bike", "plane" };
    for (int i = 0; i < 3; i++) 
    {

        ofstream out_file("C:\\Users\\Gadr\\Desktop\\test.txt");
        out_file << vehicle[i] << endl;
        out_file.close();
    }
  • 1
    `ofstream out_file("C:\\Users\\Gadr\\Desktop\\test.txt");` should be outside of the loop. As you have it, it creates a new file every iteration. – πάντα ῥεῖ Oct 31 '22 at 22:41
  • Thanks. great thinking, but that doesn't solve the main problem – urbanc cladr Oct 31 '22 at 22:46
  • 1
    Or if it should really be in the loop, use *"append"* [open mode](https://en.cppreference.com/w/cpp/io/ios_base/openmode). – Jarod42 Oct 31 '22 at 22:46
  • 2
    @urbanccladr what _"main problem"_?? That's your **main problem** so far, period. Closing the file inside the loop is wrong as well. – πάντα ῥεῖ Oct 31 '22 at 22:54
  • 1
    urbanc, I think you need to better expand on your goal. without more information, what πάνταῥεῖ suggests is where I'd start and what Jarod42 suggests is probably where I'd finish. If you need something weird, you should outline it otherwise you'll get path of least resistance answers. – user4581301 Oct 31 '22 at 23:16

1 Answers1

2

you should move both openning the stream and closing it to the outside of your loop.

string vehicle[3]= { "car", "bike", "plane" };
ofstream out_file("C:\\Users\\Gadr\\Desktop\\test.txt");
for (int i = 0; i < 3; i++) 
{

    out_file << vehicle[i] << endl;
}
out_file.close();

Ahmed AEK
  • 8,584
  • 2
  • 7
  • 23
  • 1
    Side note: Most of the time you don't need to bother with manually closing the file. Through the magic of [RAII](https://stackoverflow.com/q/2321511/4581301), file streams take care of themselves. – user4581301 Oct 31 '22 at 23:09