i think you know about the put-pointer.
it states where the next output operation will take place.
you must know that
myfile in
main() is a totally different object than the one in
hi().
each time you call
hi(), the
myfile is constructed again and opens the file for output operations, this removes previous data stored in that file and then writes the word
Hi to that file.
after the 4 calls to
hi(), you try to write the word
Hello to that file, the problem is you're trying to write it via the stream inside
main(), this stream's put-pointer still points to the beginning of the file, that means the word
Hello will overwrite the previous word existed in that file.
for the sake of demonstration, consider switching the work of
hi(), let
hi() print the word
Hello and
main()
calls
hi() 4 times then writes the word
Hi to the file, just as follows:
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 27 28
|
//Example code
#include<iostream>
#include<fstream>
void hi()
{
ofstream myfile;
myfile.open ("assignment.txt");
myfile<<"Hello"<<endl;
return 0;
}
int main()
{
ofstream myfile;
myfile.open ("assignment.txt");
if (myfile.fail())
{
cout<<"error"<<endl;
exit(1);
}
for (int i = 0; i<3; i++)
{
hi();
}
hi();
myfile<<"Hi"<<endl;
myfile.close();
return 0;
}
|
the output file shall now contain:
Hillo
hope that was clear enough.