How to import/read in data from file into a struct

Hi, will be very grateful if anyone can help me out with this, cant seem to figure out how to do it, pretty new to c++, have done the basics up to structures + file reading so far at college, starting classes + pointers soon..anyway..

i need to change the bit thats in bold (which currently initialises values of student reg. numbers + marks(only marks[0] at the moment) and instead of this, read in the data from a file in the form where each line of the file contains:

ID Mark1 Mark2 Mark3 Mark4
[see end]


-currently weve done ifstream/ofstream things, such as ifstream myfile("Test.txt"); and myfile>>PIN[counter]; but nothing on how to read data into a struct


Very grateful for any help whatsoever, [ignore the Gwin. commands, its a library we use at college]

Thanks in advance

// Session8X_4.cpp :File reading into Structures
#include "stdafx.h"
#include "gwin.h"

#include <iostream>

using namespace std;
const int NMax =10;
const int NModules =4;
struct Pupil
{
int Registration;
double Marks[NModules];
}; //NOTE the final semi-colon

int main()
{
Pupil TheClass[NMax] ;


Gwin.clear();

for (int i=0;i<NMax; i++)
{
TheClass[i].Registration = 1100-i;
TheClass[i].Marks[0] = rand()%101;
}



for (int i=NMax-1; i>0; i--)
{
for (int j=0; j<i; j++)
{
Pupil temp;
if (TheClass[j].Marks[0]>TheClass[j+1].Marks[0])
{
temp = TheClass[j];
TheClass[j]= TheClass[j+1];
TheClass[j+1]= temp;
}
}
}
for (int i=0; i<NMax; i++)
{
Gwin.writeInt(i*60, 40, TheClass[i].Registration); //output reg
Gwin.writeDouble(i*60, 60, TheClass[i].Marks[0]); //output marks[0]

}

// Finally, wait for a key to be pressed
Keyboard.getch();

return 0;
}




FILE TO BE READ IN:

1091 58 65 87 18
1092 23 45 35 39
1093 66 55 44 33
1094 33 44 55 66
1095 66 77 88 99
1096 15 55 15 55
1097 60 70 90 80
1098 99 99 99 99
1099 11 9 55 23
1100 37 14 17 24
Last edited on
Doesn't this work?

That is just an example I didn't go through your code to look at the specifications.
1
2
3
4
5
6
7
8
9
10
11
12
13
struct a
{
int b;
};

int main()
{
a a_struct;
// ifstream def here
in_file >> a_struct.b;

return 0;
}
Last edited on
I can see where your coming from, but i think the problem is because there are different 'types' in the struct, such as int Reg, and Marks[Arrayof4] ..and the text file where i am reading from contains all the info in 1 [ separated by spaces]...so how would i go about reading each 'type' into whichever ever 'type' it belongs to in the stuct
1
2
3
4
5
for (int i = 0; i < Nmax, ++i) {
    in_file >> TheClass[i].Registration; // put first into Registration;
    for (int j = 0; j < 4; ++j)
        in_file >> TheClass[i].Marks[j]; // put the rest into marks of the correct index;
}
Topic archived. No new replies allowed.