gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:39:29 24 4
gpt4 key购买 nike

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

以下是作业说明:

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com