Michael Santoro Michael Santoro - 1 month ago 10
C++ Question

Can't pass filestream as function parameter?

Here is my code for an assignment I have. Whenever I try and compile I get an error for my read function due to something in "ios_base.h" I am not sure what to do and/or if my code does the intended function of taking a file and moving it's elements into a separate file that has the name and average next to each other.

#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>

using namespace std;

struct Student
{
string fname;
string lname;
double average;
};

int read(ifstream, Student s[]);

void print(ofstream fout, Student s[], int amount);


int main()
{
const int size = 10;
ifstream fin;
ofstream fout;
string inputFile;
string outputFile;
Student s[size];

cout << "Enter input filename: ";
cin >> inputFile;
cout << "Enter output filename: ";
cin >> outputFile;
cout << endl;

fin.open(inputFile.c_str());
fout.open(outputFile.c_str());

read(fin , s);
print(fout, s, read(fin, s));

}

int read(ifstream fin, Student s[])
{
string line;
string firstName;
string lastName;
double score;
double total;
int i=0;
int totalStudents=0;
Student stu;

while(getline(fin, line)){
istringstream sin;
sin.str(line);

while(sin >> firstName >> lastName){
stu.fname = firstName;
stu.lname = lastName;

while(sin >> score){
total *= score;
i++;
}
stu.average = (total/i);
}
s[totalStudents]=stu;
totalStudents++;
}
return totalStudents;
}

void print(ofstream fout, Student s[], int amount)
{
ostringstream sout;
for(int i = 0; i<amount; i++)
{
sout << left << setw(20) << s[i].lname << ", " << s[i].fname;
fout << sout << setprecision(2) << fixed << "= " << s[i].average;
}
}

Answer

Stream objects are not copyable. Their copy constructor is deleted. They must be passed by reference, not by value:

int read(ifstream &, Student s[]);

void print(ofstream &fout, Student s[], int amount);

etc...