Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ ifstream not reading \n?

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.

like image 676
PulsePanda Avatar asked Mar 29 '13 15:03

PulsePanda


People also ask

How do you read a new line in C++?

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.

Does Ifstream need to be closed?

Do you need to close an ifstream? No, this is done automatically by the ifstream destructor.


2 Answers

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)

like image 79
Jonathan Wakely Avatar answered Oct 08 '22 13:10

Jonathan Wakely


I guess you are looking for this: instream.unsetf(std::ios_base::skipws)

like image 30
Afterbunny Avatar answered Oct 08 '22 15:10

Afterbunny