如何将文件传递给函数
How to pass a file into a function?
我很难理解如何将文件传递到函数中。
我有一个有20个名字和20个考试成绩的文件,需要由一个函数读取。然后,该函数将把名字和分数分配给一个名为student的结构。
我的问题是如何用适当的参数编写函数调用。? 使我的函数读取文件中的数据。谢谢。
// 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;
}
将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
对文件对象的引用似乎是好的,但是StudentType对象的数组可能是错误的。试试这个:
void ReadStudentData(ifstream& infile,
std::vector<StudentType>& vecStudents,
int& numStudents)
相关文章:
- 用C++在单独的头文件中完成函数体
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 头文件、宏和内联函数c++
- 如何使用单独文件中的派生类访问友元函数对象
- C++无法定义虚拟函数 OUTER 类和头文件
- 回溯C++不打印函数,因此文件
- 如何从另一个文件继承私有成员变量和公共函数
- 从函数角度看ID到文件路径的内部与外部映射
- 区分非成员函数和头文件中的成员函数
- 如何使用对C函数和类对象的外部调用来处理C++头文件
- 如何在其他文件中使用函数
- 整数键映射到头文件中的成员函数指针
- C++(.cpp文件和.h文件)拆分代码并添加一个函数,提取 - 这很容易吗?
- 给定一个C++嵌套的私有结构类型,是否有从文件范围静态函数访问它的策略
- 用"=default"声明的函数应该只在头文件中执行
- 将单独的头文件和类定义文件链接到主函数文件 - G++ 返回重载"undefined reference to"构造函数
- C++ - 在一个函数/文件中初始化变量然后在main()/另一个文件中使用它的最佳方法是什么?
- C++单独的函数文件
- 只对单个函数/文件启用编译器优化