2011-04-11 165 views
5

我很難理解如何將文件傳遞給函數。如何將文件傳遞給函數?

我有一個文件有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

您目前的代碼面臨的問題是什麼?我發現,你正在傳遞參數。 – iammilind 2011-04-11 04:25:10

回答

0

到文件對象的引用似乎是罰款,但StudentType對象的數組可能是錯誤的。 試試這個:

void ReadStudentData(ifstream& infile, 
std::vector<StudentType>& vecStudents, 
int& numStudents) 
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 
+0

這有一個作業的氣味, OP可能無法使用矢量,並被告知使用原始數組......並且此時問題已有2年的歷史。 – Casey 2013-08-16 14:46:10