简体   繁体   English

从文件中读取并存储到数组 C++

[英]reading from file and storing into array C++

I need to write a function that reads from a file and store the values into parallel arrays.我需要编写一个从文件读取并将值存储到并行数组中的函数。 In the text file I have a name and on the next line I have a set of 4 scores.在文本文件中我有一个名字,在下一行我有一组 4 个分数。 Any tips on how to achieve this.关于如何实现这一目标的任何提示。 here is an example of the text file这是文本文件的示例

joe
30 75 90 88
ben 
100 75 93 20

now here is the code I have so far现在这是我到目前为止的代码

ifstream input;

int main()
 {
string nameArray[];
double grades[];
void nameGrade(string[], double[]);

input.open("scores.txt");

nameGrade(nameArray, grades);

for (int i = 0; i <4; i++)
{
    cout << "student name: " << nameArray[i] << " Student Grades: " << grades[i] << endl;
}
input.close();
return 0;
}

void nameGrade(string name[], double grade[])
{
    for (int i = 0; i < 5; i++)
    {
        getline(input,studentName[i]);
        input >> studentGrade[i];
    }
}

Since there is only 1 name per record and multiple grades, per record, move the reading of the name before the for loop:由于每条记录只有 1 个名称和多个等级,因此每条记录将名称的读取移动到for循环之前:

void nameGrade(string& name,
               double grade[])
{
    getline(input,name);
    for (int i = 0; i < 5; i++)
    {
        input >> studentGrade[student_index * 5 + i];
    }
}

There is a complication in your design.您的设计存在复杂性。 Each student has more than one grade.每个学生都有不止一个年级。 Thus to handle this relationship, you will need either a 2 dimensional array of students or an array of structures:因此,要处理这种关系,您将需要一个二维学生数组或一个结构数组:

struct Student_Name_Grades
{
  std::string name;
  std::vector<double> grades; // substitute array here if necessary.
};
std::vector<Student_Name_Grades> student_info;
// Or:  Student_Name_Grades student_info[MAXIMUM_STUDENTS];

Another alternative is to have 5 times as many grades slots as there are students.另一种选择是拥有 5 倍于学生人数的成绩名额。 So to access the grades of student #2:因此,要访问学生 #2 的成绩:

const unsigned int GRADES_PER_STUDENT = 5;
unsigned int student_index = 2;
double grade_1 = grades[student_index * GRADES_PER_STUDENT + 0];
double grade_2 = grades[student_index * GRADES_PER_STUDENT + 1];
double grade_3 = grades[student_index * GRADES_PER_STUDENT + 2];
double grade_4 = grades[student_index * GRADES_PER_STUDENT + 3];
double grade_5 = grades[student_index * GRADES_PER_STUDENT + 4];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM