do while, while, and eof

I have to write this program that reads from a file. The file contains a first name, last name, and an unspecified number of grades. I have to display the last name, first initial followed by the average.

Right now, I'm just trying to get my loops working, but I am running into an infinite loop. I can't seem to get it to stop looping at the eof. I'm just kind of testing out the looping structure so far. I haven't actually written any of the calculation code yet.

I was just going to try printing the file out as it is to test to see if I had it right, but when it gets to the end it starts printing out infinite 0's.

Why is it printing 0s instead of terminating the program? Here is an example of the test file:

John Doe 70 80
Steve Smith 55 85 95
Bill Thomas 80 85

Here is what I have so far:

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
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>

using namespace std;

int main(){

	ifstream inFile;
	inFile.open("prog8Data.txt");

	char next = 'a';

	do
	{
		
		while(next != '\n')
		{
			inFile.get(next);
			cout << next;	
		}
		next = '1'; //I put this is so next isn't the newline char and will continue

	}
	while(!inFile.eof());

	inFile.close();
	system("pause");
	return 0;
}


Thanks for the help!
while(next != '\n')

There is no newline after the last line of the file. Why don't you read every character including the newlines? You can read a single line from the file using std::getline. i.e.

1
2
3
4
5
6
7
string lineFromFile;

while( !inFile.eof() )
{
    getline( inFile, lineFromFile );
    //process the line
}
What I was doing above was just a test to get my loops working correctly. I have to do more than just print it out.

I can't do it that way because I need to capture the names and grades into separate variables. We are only allowed to use topics we have covered so far in class, and we haven't covered any kind of string parsing yet, so I couldn't get the names and grades from the string.


The no newline after the last line of the file is helpful. Thanks for that. I will go play with my code some more.
Topic archived. No new replies allowed.