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

标签 c++ arrays struct

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

以下是作业说明:

-您将从输入文件 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 看起来有点“干净”。我考虑过在调用 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

关于c++ - 从文件中读取数据并存储到结构数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29814933/

相关文章:

sql - SQL 表与结构数组有何不同? (就用法而言,而不是实现)

struct - Golang - 嵌套结构中的 slice

C++多线程互斥锁 "reset"

c++ - 带有头文件的纯函数文件总是导致 undefined reference

c++ - 如何在已经使用适用于 C++ 的 Google Play 游戏服务 SDK 实现排行榜的情况下创建 Google+ Plus One 按钮?

在C中将字符串的尾部复制到另一个数组中,无引用无指针

c++ - 尝试使用 tensorflow 的 C++ API 时出错

java - 两个大小为 100 万的数组中的第一个公共(public)数字

c++ - 在函数内修改多维数组

python - 使用 Python/Cython 编写二进制文件的更快方法