I'm trying to do operations per-line of a text file, and the way I have it right now, my ifstream
object isn't detecting the \n
character for each line, which is required for this project. Here's how I have it right now:
std::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
file:
LXXXVII
cCxiX
MCCCLIV
CXXXLL
MMDCLXXIII
DXLCC
MCdLxxvI
XZ
X
IV
Exactly like that. I cannot change it.
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)