eof looping one to many times.

When there is white space at the end of my file, the loop loops one to many times. When there is no white space at the end of the file everything works fine. I have tried to use the suggestions on the other post but none seem to work. I need this to work the same with or without white space at the end of the file.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
 
cnt = 0;    // Loop counter.


    
// Prime the pump.
inFile >> sList[cnt].ID >> sList[cnt].hours
        >> sList[cnt].GPA;

while(!inFile.fail())		// Loop will run until eof true.
{
   // The loop breaks when eof is true or
   // when the max of amout of students, -1 for
   // 0 based indexing, is true.
   if(inFile.eof() || cnt >= MAX_STUDENTS - 1)
   {
	// Check to see if max amount of students is
	// greater than count and outputs message to
	// let user know why whole file is not read.
	if(cnt >= MAX_STUDENTS - 1)
	{
           cout << setw(4) << "\tI can only store " << MAX_STUDENTS
	        << " items in each struct type.\n\n";
	}

        break;
   }

   ++cnt;

// Read the contents of the file and store in
   // array of struct.
   inFile >> sList[cnt].ID >> sList[cnt].hours
          >> sList[cnt].GPA;
}


Please help, I assume it is something easy but I have been in a slump the last few weeks.

Thanks for you time.
Last edited on
numeric formatted input (I assume GPA is a number), performed by >> sList[cint].GPA, is required to set eofbit if the last character in the file is a digit, and not set eofbit if there was something else after that character (e.g. whitespace, in your case).

To consume whitespace from the input file, you can use the I/O manipulator std::ws, like so (I also fixed your code duplication)

1
2
3
4
5
6
7
8
9
10
    cnt = 0;
    while(cnt < MAX_STUDENTS && inFile >> sList[cnt].ID >> sList[cnt].hours >> sList[cnt].GPA >> std::ws)
    {
        ++cnt;
    }

    if(!inFile.eof() && cnt == MAX_STUDENTS)
    {
        std::cout << std::setw(4) << "\tI can only store " << MAX_STUDENTS << " items in each struct type.\n\n";
    }

this only prints the message if after processing MAX_STUDENTS entries, there is something that's not whitespace in the file.

ways to improve:
Use vectors
Give your struct an operator>> so it becomes inFile >> sList[cnt]
If the input format is three numbers per line, then use line-oriented input (while(getline(inFile, line), and parse that, instead of allowing free-flow as it does now.
You are correct about GPA being a number and thanks for the help.
Topic archived. No new replies allowed.