Having trouble reading from a text file

I created this function to read line entries from a text file. I created a for loop using the “stuFile” variable to act as a bool data type so that the loop would execute until there were no more lines to read. The for loop also increments the “i” variable so that I can keep count of how many entries there are. Everything works fine in the function as far as reading from the file goes . The issue comes when the output to the console is displayed, there is always and extra number for example:
1) Tommy 1245
2) Jake 2354
3) Kate 8546
4)
There are only 3 entries in the file so I’m not sure why I’m getting this extra number can anyone help?

void list()
{

ifstream stuFile;
string entry;
stuFile.open("Students.txt");

for (int i=1; stuFile; i++)
{
getline(stuFile, entry);
cout << i << ") " << entry << endl;
}
stuFile.close();
}
Don't you need to specify in the for loop of how bit it is?

stuFile <= 10; for example.

If there is some extra stuff beeing printed out it often mean that you read outside of the memory. That's bad.
@Andre Ekblom

You get the number 4 printed, because the cout prints it before it finds out that entry is empty, meaning end of file reached. Here is your list() routine, made into a small program. I had to add a score variable to put the numbers into. I created the 'Students.txt', and this program printed all three lines, then stopped.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Students.cpp : Defines the entry point for the console application.
//

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
	string entry;
	int score, i;
	i=1;
	ifstream stuFile;
	stuFile.open("Students.txt");

	while ( stuFile >> entry >> score )
	{
		cout << i << ") " << entry << " " << score << endl;
		i++;
	}
	// stuFile.close();  // Not needed. File closes automatically at end of reading
}
Last edited on
Topic archived. No new replies allowed.