Bone Onézimosz
Bone Onézimosz

Reputation: 3

C++ ifstream working when not existing file and not working if existing file

i wrote a code and it works perfect. But after 1 week i opened it again and i've got a very interesting probelem, so here is:

ifstream file;
file.open("bemenet.txt");

int i = -1;

while (i < SOR)
{
    i++;
    file >> termekek[i].termek;
    file >> termekek[i].ara;
    file >> termekek[i].darab;


}

file.close();

in this case bemenet.txt is exist, the program is compilated and when i try to run: i've got the error code: 0xC0000005

another case is bemenet2.txt is not exist, the program is compilated and works, but ofc when i want to see what data i've got from files it runs to infinite loop.

can you help me? i don't know what would i do...

Upvotes: 0

Views: 78

Answers (2)

marom
marom

Reputation: 5230

I would go for something like this:

ifstream file;
file.open("bemenet.txt");

TERMEK t ;
std::vector<TERMEK > termekek ;

while (file >> t.termek >> t.ara >> t.darab  )
    termekek.push_back(t) ;

Upvotes: 1

user4581301
user4581301

Reputation: 33931

ifstream file;
file.open("bemenet.txt");

int i = 0;

while ((i < SOR) && file >> termekek[i].termek >> termekek[i].ara >> termekek[i].darab  )
{
    i++;
}

file.close();

while (file >> termekek[i].termek >> termekek[i].ara >> termekek[i].darab) will test just about every IO and conversion condition you will care about--open failure, end of file, data conversion failure, sundry IO read errors--thanks to iostream's boolean operator and (i < SOR) && prevents overflow. Note i is now incremented after read and before the next test removing the possibility of the off-by-one error allowing i to get past SOR.

Upvotes: 1

Related Questions