【发布时间】: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 >> arr[],但它似乎不太可能起作用或有意义。
【问题讨论】:
-
为此,您可以简单地在循环中使用普通输入运算符
>>。您可能想了解operator>>重载。另请阅读Why is iostream::eof inside a loop condition considered wrong?。 -
FWIW,我回答了一个类似的问题 - 展示了如何编写自定义
operator>>- here。