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

时间:2016-04-18 15:05:56

标签: c++ arrays ifstream parallel-arrays

我需要编写一个从文件中读取并将值存储到并行数组中的函数。在文本文件中我有一个名字,在下一行我有一组4个分数。有关如何实现这一目标的任何提示。 这是一个文本文件的例子

joe
30 75 90 88
ben 
100 75 93 20

现在这是我到目前为止的代码

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

1 个答案:

答案 0 :(得分:1)

由于每条记录只有1个名称,每个记录有多个等级,因此在for循环之前移动名称的读数:

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

您的设计存在复杂性。每个学生都有不止一个年级。因此,要处理这种关系,您需要一个2维的学生数组或一系列结构:

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

另一种选择是拥有5倍于学生的成绩。所以要获得学生#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];