Explanation why it doesn't return what it should

时间:2018-06-04 17:32:24

标签: c++

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.

1 个答案:

答案 0 :(得分:2)

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