C++ ifstream not reading \n?

PulsePanda picture PulsePanda · Mar 29, 2013 · Viewed 23k times · Source

I'm doing a project for school, and i have to read a file, and do stuff with it. that isnt important though. i'm supposed to do the operations per line, and the way i have it right now, my ifstream object isnt detecting the '\n' character for each line, which is required for this project. here's how i have it right now:

ifstream instream;
instream >> value;
while(value != '\n')
    //do code and such

but when i have it run the loop, all i'm getting is a single line of everything in the program. while, it is doing exactly what it is supposed to in the loop, i NEED the \n to be recognized. here's my .txt document:

LXXXVII
cCxiX
MCCCLIV
CXXXLL
MMDCLXXIII
DXLCC
MCdLxxvI
XZ
X
IV

exactly like that. i cannot change it. any assistance as to what i can do would be greatly appreciated! thanks a ton!

EDIT: also, how would i be able to detect when i'm at the end of the file? thanks :D

Answer

Jonathan Wakely picture Jonathan Wakely · Mar 29, 2013

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)