View Single Post
  #5 (permalink)  
Old 08-03-2007, 06:33 PM
Bench Bench is offline
Full Programmer
Join Date: Jul 2007
Location: UK
Posts: 113
iTrader: (0)
Bench is on a distinguished roadBench is on a distinguished roadBench is on a distinguished roadBench is on a distinguished roadBench is on a distinguished road
When reading lines from files in a loop, the best place to put the getline is inside the while condition itself - this is the simplest way to make sure the file doesn't read over the end, and that the final iteration of the loop doesn't cause undefined behaviour
Code:
string str;
while( getline( infile, str ) )
{
    // ... str was read from infile OK
}

Sometimes its necessary to put the getline elsewhere, maybe if the sequence of file reads is a more complicated process, you want to put checks at every point along the way make sure each step is successful
Code:
string str;
int i;
while( true )
{
    infile >> i;
    if ( !infile )
        break;

    getline( infile, str );
    if ( ! infile )
        break;
    // read was successful - can do something with str and 'i'
}

__________________

Digg this Post! Del.Icio.Us this Post! Technorati this Post! Furl this Post! Mister Wong this Post! Newsvine this Post! Spurl this Post! Reddit this Post! Netscape this Post!

Last edited by Bench : 08-03-2007 at 06:44 PM.
Reply With Quote