LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   explain eof in c programming. (https://www.linuxquestions.org/questions/programming-9/explain-eof-in-c-programming-4175448435/)

batman4 02-03-2013 03:29 AM

explain eof in c programming.
 
i am clearing my concepts on programming and figured out this concept of eof using getchar()
This program never prints the number of characters inputted in getchar .

please help
where n how it gets eof
and why is it not printing tota number of counts


Code:


#include<stdio.h>
main(){
int c ,count;
while ((c=getchar())!=EOF)
count++;
printf("%d characters /n",count);
}


millgates 02-03-2013 09:03 AM

1) it should be int main().
2) you should initialize count before you use it.
3)
Code:

printf("%d characters /n",count);
maybe you meant
Code:

printf("%d characters \n",count);
Anyway, the program should work.

Quote:

Originally Posted by batman4
where n how it gets eof

EOF is a special value that indicates that the end of the file has been reached. If the input is read from the terminal, you can indicate the end of input by pressing Ctrl+D.

drunkenbrawler 02-06-2013 06:58 PM

http://www.cplusplus.com/reference/cstdio/EOF/

A good site for checking out definitions in C. :)

Sergei Steshenko 02-07-2013 01:26 AM

Quote:

Originally Posted by millgates (Post 4883580)
...
Anyway, the program should work.
...


I don't think so - 'count' is uninitialized.

B Akshay 02-07-2013 06:33 AM

I guess this would work!!!

Code:

#include<stdio.h>
int main(){
int c ,count=0;
while ((c=getchar())!=EOF)
count++;
printf("%d characters /n",count);
return 0;
}


EOF is the end charater specifying the end of charaters(readable) in a FILE

NevemTeve 02-07-2013 07:33 AM

Note: you're allowed to use indentation:
Code:

/* somenamehere.c */

#include <stdio.h>

int main (void)
{
    int c, count=0;

    while ((c=getchar())!=EOF)
        count++;
    printf ("%d characters\n", count);
    return 0;
}


theNbomr 02-07-2013 09:16 AM

Note that getchar() reads stdin. If the stdin stream is not redirected at runtime, then the program can never see EOF because EOF would signify closure of the console and that would also normally terminate the program. Redirecting stdin from a file will cause EOF to be seen when the file is exhausted.

The exercise might be more meaningful if used on a file or device.

--- rod.

NevemTeve 02-07-2013 09:20 AM

Or if you press Ctrl+Z (WinDos) or Ctrl+D (unix).


All times are GMT -5. The time now is 12:10 AM.