C++ ifstream not reading \n?

You can read your file as follows:

 ifstream instream("file.txt);
 string line;
 while (instream >> line)
 {
    cout << line;
    if (instream.peek() == '\n') //detect "\n"
    {
       cout <<endl;
    }
 }
 instream.close();

This way you can track where the line in file ends and detect end of file.


The >> operator does a "formatted input operation" which means (among other things) it skips whitespace.

To read raw characters one by one without skipping whitespace you need to use an "unformatted input operation" such as istream::get(). Assuming value is of type char, you can read each char with instream.get(value)

When you reach EOF the read will fail, so you can read every character in a loop such as:

while (instream.get(value))
  // process value

However, to read line-by-line you could read into a std::string and use std::getline

std::string line;
while (getline(instream, line))
  // ...

This is an unformatted input operation which reads everything up to a \n into the string, then discards the \n character (so you'd need to manually append a \n after each erad line to reconstruct the original input)