Different Ways to Write to File

What's the difference between these two source codes that do exactly the same thing? Is one method safer than another?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main()
{

ofstream File("File.txt");
string array[10];  


for (int x = 0; x <= 9; x++)
{
cout<< x <<" Enter a string:"<<endl;
cin>> array[x];
File<< array[x] << ", ";
cout<<endl;
}


return 0;
}

Note: I'm pretty sure I learned to write to files this way from C++ For Dummies (7 in 1) by Jeff Cogswell


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main()
{

fstream File;
string array[10];  

File.open("Data.txt", ios::out);

if (File.is_open ()) {
for (int x = 0; x <= 9; x++)
{
cout<< x <<" Enter a string:"<<endl;
cin>> array[x];
File<< array[x] << ", ";
cout<<endl;
}
}
File.close();

return 0;
}

Note: code above was learned from "Game Programming All In One" by Bruno Miguel Teixeira de Sousa [2002]
Last edited on
The top opens an fstream with the default parameters through the constructor of an fstream, and the bottom simply opens it separately (with possibly different parameters). They are both fine, but generally you should try to use the constructor to do the creation of the object instead of doing it separately.
@firedraco - Are you saying the top one is better than the bottom one?
Yes. It takes less time to write and you don't have to remember to put the open call.

BTW: on the top one you forgot to close the file.
Last edited on
Topic archived. No new replies allowed.