eof problem?

i have this code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
	fstream file_io;
	int i = 1;
	string file_name = "";
	cout << "enter file name: ";
	getline (cin, file_name);
	file_io.open (file_name.c_str());
	while (!file_io.eof() && i <= 50) {
		file_io << "test no. " << i << endl;
		++i;
	}
	file_io.close();
	cout << "press ENTER or ctrl-c to end the program";
	cin.get();
	return 0;
}


and i have this test file (test.txt) that contains;
a
b
c
d
e
f
g
h



but the problem is, why doesn't eof detect the end of file, and instead while keep loops until i > 50 ? in another words, the results is:
test no. 1
test no. 2
test no. 3
test no. 4
test no. 5
test no. 6
test no. 7
test no. 8
test no. 9
test no. 10
test no. 11
test no. 12
test no. 13
test no. 14
test no. 15
test no. 16
test no. 17
test no. 18
test no. 19
test no. 20
test no. 21
test no. 22
test no. 23
test no. 24
test no. 25
test no. 26
test no. 27
test no. 28
test no. 29
test no. 30
test no. 31
test no. 32
test no. 33
test no. 34
test no. 35
test no. 36
test no. 37
test no. 38
test no. 39
test no. 40
test no. 41
test no. 42
test no. 43
test no. 44
test no. 45
test no. 46
test no. 47
test no. 48
test no. 49
test no. 50
Last edited on
Where in your loop have you actually read the file? The eof() condition should only occur when reading the file.


so should i extract line by line to keep it "moving" to the next line like this:

1
2
3
4
5
string some_string = "";
while (!file_io.eof()) {
     file_io >> some_string;
     file_io << "test no. " << i << endl;
}


?
In my opinion, since you really don't seem to have a very good grasp on file reading and writing, I recommend you either read from or write to the file, not both at the same time. If you keep adding things to the file then reading them you will never get to the end of file. But in the snippet you have shown above if the file is empty to start then you will never read or write to that file because your first read will trigger eof() if the file is empty. Once the stream is in an error state no further processing of that stream is possible until you clear the error.

can you give an example?
Topic archived. No new replies allowed.