Hi y'all, I'm a c++ student and was practicing file operations this morning, when a problem caught my attention.
I was coding a program which should have read informations from a simple text file, and then should have printed them on screen. The informations are stored in an array of structured data, containing multiple arrays for each information. By removing lines of code to check which was causing my problem, I found out that the while loop is causing the crash. I really don't know the reason. Please help me, and thanks in advance.
Let's start:
1) age and score arrays are too small: you need at least 3 character array to stor 2 character c-string (do not forget about trailing zero)
2) Empty line between records are going to mess you up. Either remove it or add respective handling into your read routine.
3) !file1.eof() How many people made same mistake... In your case you should make end of file handling entirely different (and also add error proofing as a side benefit)
4) typedefstruct player {/*...*/} t_player; This is C++. You can simply do struct t_player {/*...*/};
while( i < 10 && // prevent buffer overflow
file1.getline( players[i].name, 20 ) &&
file1.getline( players[i].surname, 20 ) &&
file1.getline( players[i].age, N ) && // why are u storing age & score to a char [] ?
file1.getline( players[i].score, N ) &&
file1.ignore( 10, '\n' ) ) // discard the blank line (i put 10 just to make sure; you can ommit the arguments entirely)
++i ;