-4

I have function that gets info about students from a file "Curent.txt".

That's the struct:

struct students {
    string CodSt;
    string NumeSt;
    string PrenSt;
    string DenDisc1;
    string MedCD1;
    string DenDisc2;
    string MedCD2;
    string DenDisc3;
    string MedCD3;
} student[50];

That's the function:

void getStudents() {
int i = 0;
ifstream ifs("Curenta.txt");
while(!ifs.eof()) {
    ifs >> student[i].CodSt >> student[i].NumeSt >> student[i].PrenSt >> student[i].DenDisc1
        >> student[i].MedCD1 >> student[i].DenDisc2 >> student[i].MedCD2 >> student[i].DenDisc3
        >> student[i].MedCD3;
    if(!ifs.eof()) {
        i++;
        cout << i;
    }
    var = i;
    ifs.close();
}

And in "Curent.txt" i have only this:

9 8 1 1 6 1 1 1 1
3 1 1 1 4 1 1 1 1
1 1 1 1 1 1 1 1 1
1 1 1 1 7 1 1 1 1

My question is why when I output variable "i", the value is just 1..

Thanks in advance.

Cristian Gira
  • 47
  • 1
  • 8
  • What are you expecting `cout << i; ` to print? `i` is an integer variable. – Paul Belanger Jun 04 '18 at 17:35
  • Recommended reading: [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). Yes, you are checking twice for end of file, but there's a lot more that can go wrong than hitting the end of a file and an easier way to do this outlined in the link. – user4581301 Jun 04 '18 at 17:41

1 Answers1

2

You should close the inputstream once you finish reading all the data, so out of the loop, not inside.

NiVeR
  • 8,872
  • 4
  • 26
  • 34