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.
In C++, if we need to read a few sentences from a stream, the generally preferred way is to use the getline() function as it can read string streams till it encounters a newline or sees a delimiter provided by the user. Also, it uses <string. h> header file to be fully functional.
Do you need to close an ifstream? No, this is done automatically by the ifstream destructor.
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)
I guess you are looking for this:
instream.unsetf(std::ios_base::skipws)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With