简体   繁体   中英

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. 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:

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. So to access the grades of student #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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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