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);
If you open a file it is being completely overwritten. Let the printfunction take an "ostream&" argument and pass your fstream to it, that is probably what you were originally trying to do anyways judging by some parts of your code that don't do anything (useful) at the present. Also, use code tags.
void printfunction(int a, int b, int c, std::ostream& out)
{
out<<"a: "<<a<<"b :"<<b<<"c: "<<c<<endl;
}
int main()
{
fstream outfile("out.txt");
for ( int i = 0; i <2; i ++)
{
int a = 0, b = 1, c = 2;
a = a + i;
b = b + i;
c= c + i;
printfunction(a,b,c, outfile);
}
outfile.close();
return 0;
}
Another option would be opening the file in append mode, but I can't really recommend that because that would require additional maintenance (clearing the file everytime you start the program anew, and that outside of the function) - the function shouldn't care where exactly it's printing it's contents anyways. This way you could also pass cout to print out on the console or a stringstream or whatever you want.