【问题标题】:Read data from file and store into an array of structs从文件中读取数据并存储到结构数组中
【发布时间】:2015-07-01 03:16:06
【问题描述】:

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

以下是作业说明:

-您将从输入文件 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;
    }
}

目前,我忽略了放入 cmets 的变量。我正在考虑放弃一个 openFile 函数,只在 main 函数中执行它,但我决定反对这样做,以使我的 main 看起来有点“干净”。在我调用 openFile 函数之后,我考虑过只做inFile &gt;&gt; arr[],但它似乎不太可能起作用或有意义。

【问题讨论】:

标签: c++ arrays struct


【解决方案1】:

我的建议:

  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

【讨论】:

    【解决方案2】:

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

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

     while (!inStream.eof())
     {
    
           inStream >> StudentData arr[SIZE];
    
     };
     inStream.close();
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-25
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多