Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I want to print data to a txt file using a void function outside the main. The p

ID: 3628438 • Letter: I

Question

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;
}

Explanation / Answer

please rate - thanks

everytime you open a file, unless it's opened for appending, you start writting at the beginning of the file.

you must open the file once in main, and pass it to the function

#include <fstream>
using namespace std;
void printfunction(ostream& outfile,int a, int b, int c)
{
outfile<<"a: "<<a<<"b :"<<b<<"c: "<<c<<endl;
}
int main()
{
ofstream outfile;
outfile.open("table.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(outfile,a,b,c);
}
outfile.close();
return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote