home bbs files messages ]

Forums before death by AOL, social media and spammers... "We can't have nice things"

   comp.lang.c++.moderated      Moderated discussion of C++ superhackery      33,346 messages   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]

   Message 32,210 of 33,346   
   Bo Persson to All   
   Re: Recommend method to read from a poss   
   27 Apr 12 11:29:16   
   
   From: bop@gmb.dk   
      
   Helmut Jarausch skrev 2012-04-26 23:24:   
   > Hi,   
   >   
   > is there a recommend way to read from an ifstream if this is possibly   
   > empty?   
   >   
   > The simple way   
   >   
   >    std::ifstream  Inp("Empty");   
   >   
   >    if ( ! Inp ) {   
   >      cerr<<  "Open failed\n";   
   >      return 1;   
   >    }   
   >   
   >    int V;   
   >   
   >    while (Inp) {   
   >      cerr<<  "--- here with while ---\n";   
   >      Inp>>  V;   
   >    }   
   >   
   > is invalid, since it enters the while loop at least once (for an empty   
   > file)   
   > The working alternative   
   >   
   >    while (Inp) {   
   >      if ( ! Inp ) break;   
   >     ....   
   >    }   
   >   
   > is ugly.   
   >   
   > Is there a recommended, readable way to do this?   
   >   
      
   The standard way to do this is   
      
        while (Inp >> v) {   
          cerr<<  "--- here with while ---\n";   
          // do something with v   
        }   
      
   which terminates the while loop when the read fails. You don't know the   
   status until you have attempted to do the read.   
      
      
   Bo Persson   
      
      
   --   
         [ See http://www.gotw.ca/resources/clcm.htm for info about ]   
         [ comp.lang.c++.moderated.    First time posters: Do this! ]   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]


(c) 1994,  bbs@darkrealms.ca