c++ - Read data from file and store into an array of structs -
so need creating program open file , read data file array of structs , calculate variety of things highest, lowest, average , standard deviation. right now, more concerned how read actual file , place array of structs.
here instructions assignment:
-you read input data input file scores.txt (will posted in etudes); , data in format (studentid, first name, last name, exam1, exam2 , exam3).
-each line of data 1 student read file , assigned struct variable. consequently, need array of structs store data read input file. 1-dimensional array.
-once read data file array, required calculate , display following statistics each exam.
here data file:
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 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 file infile.open(infilename); //input validation if (!infile) { cout << "error open file." << endl; cout << endl; return; } }
for moment, ignoring variables put comments. thinking forgoing openfile function , doing in main function decided against make main bit "cleaner". considered doing infile >> arr[]
after called openfile function seemed unlikely work or make sense.
my suggestion:
- add operator function read 1
studentdata
object stream. - add
while
loop inmain
. in each iteration of loop, readstudentdata
std::istream& operator>>(std::istream& in, studentdata& st) { return (in >> st.studentid >> st.first_name >> st.last_name >> st.exam1 >> st.exam2 >> st.exam3); }
and in main
:
openinputfile(infile, infilename); size_t numitems = 0; while ( infile >> arr[numitems] ) ++numitems;
at end of that, have read numitems
items arr
.