Ben Payne wrote:
I think the most concise, and foolproof way to do this is just:
while(!infile.getline(temp1, max).eof());
this is valid since getline returns a reference to the stream.
the only downside is addition of a function call, but that's
what it's there for.
ARGH! THIS WILL NOT WORK! (Sorry for the shouting, but...)
Note that any given getline() call can successfully read data from the
input stream into 'test1' and, in the process of doing so, detect the
end-of-file condition (and consequently set the stream's eofbit state
flag). IOW, a single getline() call can both read data into 'test1'
*AND* set the stream's eofbit state flag. So your while(!eof) loop
introduces an "off by one" error for this particular case -- i.e., the
program reads some data from infile into test1, it detects/reports the
EOF condition, and the while() loop exits. Notice that the last bit of
file data in 'test1' IS NOT PROCESSED BY THE PROGRAM -- i.e., the data
in test1 is not processed by the code in the body of the while() loop --
because the EOF condition caused the program to break out of the while()
loop too soon! Whoops...
FWIW, this is one of two different "off by one" logic errors that *will
occur* when you write a loop construct like this,
while ( ! end-of-file on an input stream ) ...
A "more better" loop test would be this:
while ( data is successfully read from infile into test1 ) {
process the data in test1;
}
e.g.,
while ( infile.getline(test1,max).gcount() ) ...
[n.b. The gcount() method returns the number of characters extracted
from an input stream object by the last unformatted input member
function(*) called on the object.
(*) e.g., the get() and getline() member functions perform unformatted input
]
FWIW2, there is yet another "gotcha" here. Note that if the getline()
call completely fills the buffer 'test1' without also reading in the
delimiter character (i.e., the buffer 'test1' is too small to hold the
entire line of input), then getline() will assert the input stream's
'failbit' flag to signal this "buffer full" condition. So the program
must also check for, and respond to, this failbit condition -- e.g.,
while ( infile.getline(test1,max).gcount() ) {
// Clear the stream's 'failbit' state flag
infile.clear( infile.rdstate() & ~ios::failbit );
...
}
--
Jim
To reply by email, remove "link" and change "now.here" to "yahoo"
jfischer_link5809{at}now.here.com