Unable to print to a txt file while inside a loop

Hey everyone,
I want to print data to a txt file using a void function outside the main. The problem is that it only prints the last iteration of the loop calling these function.

it only prints: a: 3 b: 4 c: 5

and a couple more things that look like garbage underneath this line of numbers

void printfunction(int a, int b, int c)
{
fstream outfile;
outfile.open("table.txt");
outfile<<"a: "<<a<<"b :"<<b<<"c: "<<c<<endl;

}

int main()
{


fstream outfile;

for ( int i = 0; i <2; i ++)
{
int a = 0, b = 1, c = 2;
a = a + i;
b = b + i;
c= c + i;
fstream outfile;
printfunction(a,b,c);

}

outfile.close();
return 0;
}

Any help would be greatly appreciated.
Try the following:

1
2
3
4
5
6
7
void printfunction(int a, int b, int c)
{
    fstream outfile;
    outfile.open("table.txt", ios_base::app); //set file pointer to the end of the file
    outfile<<"a: "<<a<<"b :"<<b<<"c: "<<c<<endl;
    outfile.close();
}


Also, there's no need to instantiate the outfile in main() since it's not being used there.
gibran, you already asked that question somewhere else. In the general section I believe.

And shacktar - append mode is an option, but hardly the best in this situation.
that did not do do the trick , i still get the same results and if i omit the fstream outfile form main(), it does not compile, error: outfile was not declared in the scope
You also need to put the outfile.close() line inside printfunction, not in main().
it does not compile, error: outfile was not declared in the scope

That's because you're calling close() on outfile which was no longer declared.

Just so nobody else responds to this thread, it's been resolved here:
http://www.cplusplus.com/forum/general/50207/
Topic archived. No new replies allowed.