从文件中读取数据并存储到结构数组中

Read data from file and store into an array of structs

所以我需要帮助创建一个程序,该程序将打开一个文件并将文件中的数据读取到一个结构数组中,然后计算诸如最高、最低、平均值和标准偏差之类的各种数据。现在,我更关心如何读取实际文件并将其放入结构数组中。

以下是作业说明:

-您将从输入文件scores.txt中读取输入数据(将发布在 练习曲);数据的格式为 (studentID, first name, last name, exam1, 考试 2 和考试 3).

-一个学生的每行数据将从文件中读取,然后分配给一个 结构变量。因此,您将需要一个结构数组来存储所有 从输入文件中读取的数据。这将是一个一维数组。

-一旦你从文件中读取数据到你的数组,你需要计算 并显示每次考试的以下统计数据。

这是数据文件:

1234 David Dalton 82 86 80
9138 Shirley Gross 90 98 94
3124 Cynthia Morley 87 84 82
4532 Albert Roberts 56 89 78
5678 Amelia Pauls 90 87 65
6134 Samson Smith 29 65 33
7874 Michael Garett 91 92 92
8026 Melissa Downey 74 75 89
9893 Gabe Yu 69 66 68

#include "stdafx.h"
#include <iostream> 
#include <string> 
#include <fstream>
#include <iomanip> 

using namespace std; 

struct StudentData
{
    int studentID; 
    string first_name; 
    string last_name; 
    int exam1; 
    int exam2; 
    int exam3; 
}; 

const int SIZE = 20; 

// Function prototypes
void openInputFile(ifstream &, string); 

int main()
{
    // Variables
    //int lowest, highest; 
    //double average, standardDeviation; 
    StudentData arr[SIZE]; 

    ifstream inFile; 
    string inFileName = "scores.txt"; 

    // Call function to read data in file
    openInputFile(inFile, inFileName);

    //Close input file
    inFile.close(); 

    system("PAUSE"); 

    return 0; 
}

/**
* Pre-condition: 
* Post-condition: 
*/
void openInputFile(ifstream &inFile, string inFileName)
{
    //Open the file
    inFile.open(inFileName);

    //Input validation
    if (!inFile)
    {
        cout << "Error to open file." << endl;
        cout << endl;
        return;
    }
}

目前,我忽略了我放入评论中的变量。我正在考虑放弃一个 openFile 函数,而只是在 main 函数中执行它,但我决定不这样做,以使我的 main 看起来有点 "cleaner"。我考虑过在调用 openFile 函数后只执行 inFile >> arr[] 但它似乎不太可能起作用或有意义。

我的建议:

  1. 添加一个运算符函数以从流中读取一个 StudentData 对象。
  2. main 中添加一个 while 循环。在循环的每次迭代中,读取一个 StudentData
std::istream& operator>>(std::istream& in, StudentData& st)
{
    return (in >> st.studentID
               >> st.first_name
               >> st.last_name
               >> st.exam1
               >> st.exam2
               >> st.exam3);
}

并在 main 中:

openInputFile(inFile, inFileName);

size_t numItems = 0;
while ( inFile >> arr[numItems] )
   ++numItems;

最后,您将成功将 numItems 项读入 arr

这应该将所有数据读入数组,您需要一个增量器

ifstream inStream; inStream.open("scores.txt");

 while (!inStream.eof())
 {

       inStream >> StudentData arr[SIZE];

 };
 inStream.close();