title: Getting std :: ifstream to handle LF, CR, and CRLF?
body: <p>Specifically I'm interested in <code>istream&amp; getline ( istream&amp; is, string&amp; str );</code>. Is there an option to the ifstream constructor to tell it to convert all newline encodings to '\n' under the hood? I want to be able to call <code>getline</code> and have it gracefully handle all line endings.</p>
  
  <p><strong>Update</strong>: To clarify, I want to be able to write code that compiles almost anywhere, and will take input from almost anywhere. Including the rare files that have '\r' without '\n'. Minimizing inconvenience for any users of the software.</p>
  
  <p>It's easy to workaround the issue, but I'm still curious as to the right way, in the standard, to flexibly handle all text file formats.</p>
  
  <p><code>getline</code> reads in a full line, up to a '\n', into a string. The '\n' is consumed from the stream, but getline doesn't include it in the string. That's fine so far, but there might be a '\r' just before the '\n' that gets included into the string.</p>
  
  <p>There are <a href="http://en.wikipedia.org/wiki/CRLF#Representations">three types of line endings</a> seen in text files:
  '\n' is the conventional ending on Unix machines, '\r' was (I think) used on old Mac operating systems, and Windows uses a pair, '\r' following by '\n'.</p>
  
  <p>The problem is that <code>getline</code> leaves the '\r' on the end of the string.</p>
  
  <pre><code>ifstream f("a_text_file_of_unknown_origin");
  string line;
  getline(f, line);
  if(!f.fail()) { // a non-empty line was read
     // BUT, there might be an '\r' at the end now.
  }
  </code></pre>
  
  <p><strong>Edit</strong> Thanks to Neil for pointing out that <code>f.good()</code> isn't what I wanted. <code>!f.fail()</code> is what I want.</p>
  
  <p>I can remove it manually myself (see edit of this question), which is easy for the Windows text files. But I'm worried that somebody will feed in a file containing only '\r'. In that case, I presume getline will consume the whole file, thinking that it is a single line!</p>
  
  <p>.. and that's not even considering Unicode :-)</p>
  
  <p>.. maybe Boost has a nice way to consume one line at a time from any text-file type?</p>
  
  <p><strong>Edit</strong> I'm using this, to handle the Windows files, but I still feel I shouldn't have to! And this won't fork for the '\r'-only files.</p>
  
  <pre><code>if(!line.empty() &amp;&amp; *line.rbegin() == '\r') {
      line.erase( line.length()-1, 1);
  }
  </code></pre>