Page 1 of 1
How do u check for eoln in C++?
Posted: Fri Apr 16, 2004 12:55 am
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...!!!

A help
Posted: Fri Apr 16, 2004 10:14 am
by Fresh
Hope this help
[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]
Posted: Fri Apr 16, 2004 9:08 pm
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.
Posted: Sat Apr 17, 2004 3:51 pm
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.