如何将文件传递给函数?

时间:2011-04-11 03:25:52

标签: c++ visual-c++

我很难理解如何将文件传递给函数。

我有一个包含20个名字和20个测试分数的文件需要由函数读取。然后,该函数将名称和分数分配给名为student的结构。

我的问题是如何使用适当的参数编写函数调用。 ?使我的函数读取文件中的数据。感谢。

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

2 个答案:

答案 0 :(得分:2)

ifstream传递给函数的方式非常好。

我怀疑问题在于您管理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

答案 1 :(得分:0)

对文件对象的引用似乎没问题,但StudentType对象的数组可能不对。 试试这个:

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