Reputation: 6255
In C, EOF
is a macro defined in stdio.h
. I wonder is there a C++ equivalent to it (a const int
or sth)?
What do I want it for? For example, I may want to implement a SeekEof()
:
// Is there any non-space character remaining?
bool SeekEof(std::istream &in) {
int c(0);
while ((c = in.peek()) != EOF &&
(c == ' ' || c == '\t' ||
c == '\r' || c == '\n')) in.get();
return c == EOF ;
}
Upvotes: 1
Views: 1010
Reputation: 263237
When reading from a file or other stream using C's <stdio.h>
functions, EOF
is a special value returned by certain functions to flag an inability to read any more data, either because you've reached the end of the file or because there was an error. There are feof()
and ferror()
functions, but these should only be used after you've detected and end-of-file or error condition, to distinguish one from the other.
For example, the classic C input loop is:
int c; /* Note int, *not* char */
while ((c = getchar()) != EOF) {
/* do something with c */
}
/* optional: */
if (ferror(stdin)) {
/* an error occurred, not just end-of-file */
}
C++'s has several different overloaded std::istream::get()
functions. One of them takes no arguments and behaves very similarly to C's getchar()
: it returns an int
value which will be EOF
if no more data is available:
int c;
while ((c = std::cin.get()) != EOF) {
// do something with c
}
You'll have to have #include <cstdio>
to get the definition of EOF
.
Another overloaded version takes a reference to a char
and returns an istream&
result that can be tested to tell whether it was able to read anything:
char c;
while (std::cin.get(c)) {
std::cout << c;
}
There is an eof()
function (specifically std::ios::eof()
) that tells you whether the end-of-file flag is set. There are several other state functions: good()
, fail()
and bad()
. See here for more information.
(NOTE: Is cplusplus.com considered a good resource? If not, let me know and I'll change the link.)
In any case, the state functions (feof()
and ferror()
for C I/O, eof()
, fail()
, bad()
, good()
for C++ I/O) should not be used as loop conditions; instead, loops should be controlled by the result you get when you attempt input, and the other functions can be used after the loop terminates to determine why it terminated.
Upvotes: 1
Reputation: 88155
std::char_traits<char>::eof()
std::char_traits<char16_t>::eof()
std::char_traits<char32_t>::eof()
std::char_traits<wchar_t>::eof()
Upvotes: 4
Reputation: 17521
You can use stdio.h
also in your c++ application. But beware of using it. its stupid (-1) macro and -1 to byte is 255 (0xff). If you check input character to EOF, you can end with result of false end of file. Safe check for eof
is using feof() in c/c++ and .eof() methods in c++.
Upvotes: 2
Reputation: 1526
std::fstream fileHandle.eof() http://www.cplusplus.com/reference/iostream/ios/eof/
Upvotes: 0