Thursday, May 30, 2019
c - feof(in) != EOF doesn't make while loop stop when at the end of file?
Answer
Answer
int main ()
{
FILE *in;
in = fopen("input.txt","r");
char c = fgetc(in);
while(feof(in) != EOF)
{
printf("%c",c);
c = fgetc(in);
}
}
feof(in) != EOF
doesn't stop the while loop from stopping but something like !feof(in)
seems to work. Any ideas?
Answer
feof
doesn't return EOF
on end of file; it returns true
, which is not equal to EOF
.
fgetc
will return EOF
when it hits end-of-file. Your code should be written as
int main ()
{
FILE *in;
in = fopen("input.txt","r");
int c = fgetc(in); // note int not char
while(c != EOF) // compare c to EOF
{
printf("%c",c);
c = fgetc(in);
}
}
You should not use feof
as a loop condition, as it won't return true
until after you attempt to read past the end of the file, meaning your loop will execute once too often.
Subscribe to:
Post Comments (Atom)
plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV
In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...
-
This question attempts to collect the few pearls among the dozens of bad C++ books that are published every year. Unlike many other programm...
-
I need to do the following: My current address looks like: https://www.domain.com I want to redirect with htaccess: www.domain.com TO https:...
-
using namespace std; So far in my computer science courses, this is all we have been told to do. Not only that, but it's all tha...
No comments:
Post a Comment