Spectre wrote:
upon executing your code i got
B E E R
But that's only your system :-)
Other systems may behave differently.
in fact i think thats a sweet idea.....
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream infile;
char x;
infile.open("temp.txt");
if( !infile.good() )
{
cout << "Error opening file" << endl;
system("PAUSE");
exit(1);
}
while( !infile.eof() )
{
infile.get(x); //reads in characters
x=toupper(x); //converts characters to upper case
cout << x << '\t';
}
eof gets true only *after* you have *tried* and *failed*
to read from the stream.
the program enters the while loop and processes 'b' 'e' and 'e'.
The next time the loop is entered the program reads the next
character: 'r'. The character is converted to upper case and
sent to cout. eof is tested again and returns false! Remember:
you need to try and fail to read from the stream.
Thus the loop is entered again and an attempt to read from
infile is made. But this time the attempt fails, since there
is nothing more in the stream that could be read. Yet your
loop body continues as if nothing has happend and converts
and outputs x. Only after that, eof will return true.
End effect: You looped one to many through the loop and
try to process a character, whose read operation from infile
has failed.
Whenever you see a loop
while( somestream.eof() )
{
read from somestream
process
}
then almost always, this is wrong. Most programmer think
this way:
as long as I have not reached the end of the file
{
read frm the file
process what has been read
}
This may work in other programming lanquages, but not in C++.
In C++ one, correct, way to think is:
as long as I can read from the file
{
process what has been read
}
why did the read fail? Was it because eof?
If yes, then everything is OK. The stream was
read completely.
or in code:
while( infile.get( x ) )
{
x = toupper( x );
cout << x << '\t';
}
if( !infile.eof() )
{
cout << "Read operation failed for unknown reasons\n";
...
}
--
Karl Heinz Buchegger
kb******@gascad.at