How to pass a file to a function?

I find it difficult to understand how to pass a file to a function.

I have a file with 20 names and 20 test results that need to be read by a function. the function will then assign names and ratings to the structure called the student.

My question is how to write a function call with the appropriate parameters.? so that my function reads the data in the file. thank.

CODE

// ask user for student file
cout << "Enter the name of the file for the student data to be read for input" << endl;
cout << " (Note: The file and path cannot contain spaces)" << endl;
cout << endl;
cin >> inFileName;
inFile.open(inFileName);
cout << endl;

// FUNCTION CALL how do i set this up properly?
ReadStudentData(inFile, student, numStudents ); 

void ReadStudentData(ifstream& infile, StudentType student[], int& numStudents)
{
    int index = 0;
    string lastName, firstName;
    int testScore;

    while ((index < numStudents) &&
           (infile >> lastName >> firstName >> testScore))
    {
        if (testScore >= 0 && testScore <= 100)
        {
            student[index].studentName = lastName + ", " + firstName;
            student[index].testScore = testScore;
            index++;
        }
    }

    numStudents = index;
}
+5
source share
2 answers

The way you pass ifstreamin the function is great.

, , StudentType (numStudents). , std::vector . , , .

, .

, , , .

#include <vector>
using namespace std;

vector<StudentType> ReadStudentData(ifstream& infile) {
    vector<StudentType> students;
    string lastName, firstName;
    int testScore;
    while (infile >> lastName >> firstName >> testScore) {
        if (testScore >= 0 && testScore <= 100) {
            StudentType student;
            student.studentName = lastName + ", " + firstName;
            student.testScore = testScore;
            students.push_back(student);
        }
    }
    return students;
}

// call the function
vector<StudentType> students = ReadStudentData(infile);

// or if you have a C++11 compiler
auto students = ReadStudentData(infile);

// use students.size() to determine how many students were read
+2

- , StudentType . :

void ReadStudentData(ifstream& infile, 
std::vector<StudentType>& vecStudents, 
int& numStudents)
0

All Articles