How do u check for eoln in C++?

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
neno_uci
Experienced poster
Posts: 104
Joined: Sat Jan 17, 2004 12:26 pm
Location: Cuba

How do u check for eoln in C++?

Post by neno_uci »

Hi, how can I check for end of line in C++, using files, I want something like this in PASCAL:
[pascal]

f : text;

while not eoln(f) do
begin
...
...
end;
[/pascal]

I feel frustrated, please help me...!!! :cry:

Fresh
New poster
Posts: 46
Joined: Mon Apr 15, 2002 10:42 am
Contact:

A help

Post by Fresh »

Hope this help :wink:

[cpp]

#include <fstream.h>

void main()
{
char str[1024];

ifstream in("data.txt");

if (in.is_open())
{
while (in.getline(str, sizeof(str)))
{
// the process is here
}

in.close();
}
}

[/cpp]

Jordan Gordeev
New poster
Posts: 14
Joined: Tue Nov 12, 2002 6:04 pm
Location: Bulgaria

Post by Jordan Gordeev »

You can read character by character until reading an end-of-line character.
This code in Pascal:
[pascal]var
f:Text;
c:Char;
while not eoln(f) do
begin
Read(f, c);
{do something with c}
end;
Readln(f);{advance to the next line}
[/pascal]
might become
[cpp]ifstream inp;
char c;
while ((c = inp.get()) != '\n') {
// do something with c
}
[/cpp]
in C++. The C++ code advances to the next line "automatically".
I think the code in C++ above is not equivalent to the one in Pascal in one particular case.
If I recall corectly, when eof(f) is true in Pascal, that is, we are at the end of the file f, eoln(f) is also true. You might want to modify the C++ code to work for that case by checking for eof in the cycle (in the cycle condition or in the cycle body) and exiting when the eof is reached.
Alternativly you might read the file line by line with the equivalent of Readln in C++ - stream_name.getline(char*, int). If you read line by line you should have a large enough buffer to hold the longest line in the file. You should know how long the longest line in the file could be.

Krzysztof Duleba
Guru
Posts: 584
Joined: Thu Jun 19, 2003 3:48 am
Location: Sanok, Poland
Contact:

Post by Krzysztof Duleba »

Alternativly you might read the file line by line with the equivalent of Readln in C++ - stream_name.getline(char*, int). If you read line by line you should have a large enough buffer to hold the longest line in the file. You should know how long the longest line in the file could be.
This is not true. One can read a line using
[cpp]getline(istream &, string &)[/cpp]
which will read the line to the string. Strings are smart enough to resize if necessary.

Post Reply

Return to “C++”