title: Detecting end of input using std::getline
body: <p>I have a code with the following snippet:</p>
  
  <pre><code>std::string input;
  while(std::getline(std::cin, input))
  {   
      //some read only processing with input
  }
  </code></pre>
  
  <p>When I run the program code, I redirect stdin input through the file in.txt (which was created using gedit), and it contains:</p>
  
  <pre><code>ABCD
  DEFG
  HIJK
  </code></pre>
  
  <p>Each of the above lines end with one newline in the file in.txt. </p>
  
  <p>The problem I am facing is, after the while loop runs for 3 times (for each line), the program control does not move forward and is stuck. My question is why is this happening and what can I do to resolve the problem?</p>
  
  <h2>Some clarification:</h2>
  
  <p>I want to be able to run the program from the command line as such:</p>
  
  <pre><code>$ gcc program.cc -o out
  $ ./out &lt; in.txt
  </code></pre>
  
  <h2>Additional Information:</h2>
  
  <p>I did some debugging and found that the while loop actually is running for 4 times (the fourth time with input as empty string). This is causing the loop to program to stall, because the <em>//some processing read only with input</em> is unable to do its work. </p>
  
  <p>So my refined question:</p>
  
  <p>1) Why is the 4th loop running at all?</p>
  
  <blockquote>
    <p>Rationale behind having std::getline() in the while loop's condition
    must be that, when getline() cannot read any more input, it returns
    zero and hence the while loop breaks.</p>
    
    <p>Contrary to that, while loop
    instead continues with an empty string! Why then have getline in the
    while loop condition at all? Isn't that bad design?</p>
  </blockquote>
  
  <p>2) How do I ensure that the while doesn't run for the 4th time without using break statements?</p>
  
  <blockquote>
    <p>For now I have used a break statement and string stream as follows:</p>
  
  <pre><code>std::string input;
  char temp;
  while(std::getline(std::cin, input))
  {       
      std::istringstream iss(input);
      if (!(iss &gt;&gt;temp))
      {    
          break;
      } 
      //some read only processing with input
  }
  </code></pre>
    
    <p>But clearly there has to be a more elegant way.</p>
  </blockquote>