Character 255 added to end?

I'm loading files with ifstream object but they always end in 'ΓΏ' (character 255 or -1). Here is my code for loading a file and printing it in a test project:
1
2
3
4
5
6
7
8
9
10
11
12
13
ifstream In (/*some file*/, ios_base::in|ios_base::binary);
if(!In.is_open())
{
	cerr << "Error" << endl;
}
else
{
	while(In.good())
	{
		cout << In.get() << ' ';
	}
	In.close();
}


And as I said, no matter which file I load, the last number it prints out is always -1. So what am I doing wrong? Is this normal and I just have to manually leave out this last character?
Last edited on
Something is amiss in the documentation of int istream::get(): http://www.cplusplus.com/reference/iostream/istream/get/.

The information is consistent with other sources, but it is written that "the function returns the character read". However, if that was the case, the return type would be char, not int. Actually the return type is extended in order to be able to return the special value EOF which appears to be defined in <cstdio> (http://www.cplusplus.com/reference/clibrary/cstdio/EOF/). But EOF is actually the integer -1.

What is important to know though, is that the error flags and the end-of-file flag are set after the fact. For example, suppose you read the last character, therefore reaching the end of the file. But the end-of-file indicator will not be set. You try to read again, the IO function you called fails miserably (but in well defined, officially documented way, I mean), and now the end-of-file indicator is raised.

So you can not check if the file can be read further before the IO operation, like at the beginning of the loop. You have to check after the IO operation. You can use the strategy:
1
2
3
4
while (cin >> ch)
{
...
}
or the strategy:
1
2
3
4
while ( (ch= cin.get() ) != EOF )
{
...
}
, but I wander, is the latter not documented officially for a reason.
Thank you for the information, I did not know that character was used. (I probably could have searched it, sorry)
Could I not use the peek member function? This code works perfectly:
1
2
3
4
5
6
7
8
9
10
11
12
13
ifstream In (/*some file*/, ios_base::in|ios_base::binary);
if(!In.is_open())
{
	cerr << "Error" << endl;
}
else
{
	while(In.good() && In.peek() != EOF)
	{
		cout << In.get() << ' ';
	}
	In.close();
}
Looking at the documentation of peek, I see no reason not to. You could even get rid of the In.good() condition, but I have not used this technique to be sure.

PS: The peek routine is more properly documented than get and mentions the EOF value:
http://www.cplusplus.com/reference/iostream/istream/peek/

Regards
Topic archived. No new replies allowed.