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,207 of 33,346    |
|    bartek szurgot to Helmut Jarausch    |
|    Re: Recommend method to read from a poss    |
|    27 Apr 12 11:28:35    |
   
   From: basz@no.spam   
      
   On 04/26/2012 11:24 PM, Helmut Jarausch wrote:   
   > 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?   
   >   
   > Many thanks for a hint,   
   > Helmut.   
      
      
   how about this:   
      
    ifstream is("empty.txt");   
    if(!is)   
    {   
    cerr << "Open failed\n";   
    return 1;   
    }   
      
    int tmp;   
    while(is && (is>>tmp))   
    {   
    cout << "--- here with while ---\n";   
    cout << tmp << endl;   
    }   
      
      
   --   
   pozdrawiam serdecznie / best regards,   
   bartek szurgot   
   /* http://www.baszerr.eu */   
      
      
    [ 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