ifstream reader and iterations

I'm reading Mike McGrath's book on C++. This page I'm on is suppose to read an inut file and count the iterations, but it goes 0 and 1. This book isn't the best but I don't want to skip the page I'd like to know what's gone wrong. Here is the full code.

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
#include <fstream>
#include <iostream>
using namespace std;

int main()
{
	char letter;
	int i;
	
	ifstream reader( "poem.txt" );

	if ( ! reader )
	{
		cout << "Error opening input file" << endl;
		return -1;
}

	for ( i = 0 ; ! reader.eof() ; i++ )
	{
		reader.get(letter);
		cout << letter;
		reader.close();
		cout << "Iterations: " << i << endl;
		
	}
}
You close the stream after the first iteration, on line 22.
Thanks, I've moved reader.close(); to the bottom but it still has the same issue. I can move it to the next } but it doesn't do the same in the book.
It's suppose to display the input file and the iterations under it cleanly. Sorry for my noobness.

EDIT: Fixed it by moving
cout << "Iterations: " << i << endl;
reader.close();

To the line 26 and it's done it right, this book is so vague or maybe I'm slow. Thanks helios! Always good to ask for help instead of giving up. :)
Last edited on
Topic archived. No new replies allowed.