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,206 of 33,346   
   Ulrich Eckhardt to All   
   Re: Recommend method to read from a poss   
   27 Apr 12 11:28:20   
   
   From: ulrich.eckhardt@dominolaser.com   
      
   Am 26.04.2012 23:24, schrieb Helmut Jarausch:   
   > is there a recommend way to read from an ifstream if this is possibly   
   > empty?   
      
   I'd use a platform-specific check for an empty file, i.e. avoid the   
   stream altogether. However, if all you have is a stream, you can do it   
   too...   
      
   >   while (Inp) {   
   >     cerr << "--- here with while ---\n";   
   >     Inp >> V;   
   >   }   
      
   This is wrong. Always(!) do the input operation first and then check for   
   failures, don't assume because a stream is in good state that an input   
   operation will not fail!   
      
   Now, concerning a test if there is something left in a stream, you can   
   peek() a character:   
      
     char c;   
     if(!in.peek(c))   
         /end-of-file reached/   
      
      
   However, this also has a few problems:   
      
     istringstream in("42\n"); // file content   
     while(in) {   
         char c;   
         if(!in.peek(c))   
             return;   
         int answer;   
         in >> answer;   
         if(answer != 42)   
             throw runtime_error("Halp!!1"")   
     };   
      
   The problem here is that reading the integer still leaves the trailing   
   newline in the file. Peeking for the next char as a test if the end was   
   reached then returns this character, but reading another integer fails.   
      
   As a remedy, use the idiomatic "while(read input){handle input}"   
   mentioned above. Alternatively, first extract any whitespace with "in >>   
   ws" before checking for the end-of-file.   
      
   Uli   
      
      
   --   
         [ 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